]> git.mxchange.org Git - friendica.git/blob - include/api.php
f7c1b8d3468730a49d0e6b80aa1d665c68744b1e
[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\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Core\System;
33 use Friendica\Database\DBA;
34 use Friendica\DI;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Group;
37 use Friendica\Model\Item;
38 use Friendica\Model\Mail;
39 use Friendica\Model\Notification;
40 use Friendica\Model\Photo;
41 use Friendica\Model\Post;
42 use Friendica\Model\Profile;
43 use Friendica\Model\User;
44 use Friendica\Model\Verb;
45 use Friendica\Module\BaseApi;
46 use Friendica\Network\HTTPException;
47 use Friendica\Network\HTTPException\BadRequestException;
48 use Friendica\Network\HTTPException\ForbiddenException;
49 use Friendica\Network\HTTPException\InternalServerErrorException;
50 use Friendica\Network\HTTPException\MethodNotAllowedException;
51 use Friendica\Network\HTTPException\NotFoundException;
52 use Friendica\Network\HTTPException\TooManyRequestsException;
53 use Friendica\Network\HTTPException\UnauthorizedException;
54 use Friendica\Object\Image;
55 use Friendica\Protocol\Activity;
56 use Friendica\Security\BasicAuth;
57 use Friendica\Security\OAuth;
58 use Friendica\Util\DateTimeFormat;
59 use Friendica\Util\Images;
60 use Friendica\Util\Network;
61 use Friendica\Util\Strings;
62
63 require_once __DIR__ . '/../mod/item.php';
64 require_once __DIR__ . '/../mod/wall_upload.php';
65
66 define('API_METHOD_ANY', '*');
67 define('API_METHOD_GET', 'GET');
68 define('API_METHOD_POST', 'POST,PUT');
69 define('API_METHOD_DELETE', 'POST,DELETE');
70
71 define('API_LOG_PREFIX', 'API {action} - ');
72
73 $API = [];
74 $called_api = [];
75
76 /**
77  * Auth API user
78  *
79  * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
80  * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
81  * into a page, and visitors will post something without noticing it).
82  */
83 function api_user()
84 {
85         $user = OAuth::getCurrentUserID();
86         if (!empty($user)) {
87                 return $user;
88         }
89
90         if (!empty($_SESSION['allow_api'])) {
91                 return local_user();
92         }
93
94         return false;
95 }
96
97 /**
98  * Get source name from API client
99  *
100  * Clients can send 'source' parameter to be show in post metadata
101  * as "sent via <source>".
102  * Some clients doesn't send a source param, we support ones we know
103  * (only Twidere, atm)
104  *
105  * @return string
106  *        Client source name, default to "api" if unset/unknown
107  * @throws Exception
108  */
109 function api_source()
110 {
111         if (requestdata('source')) {
112                 return requestdata('source');
113         }
114
115         // Support for known clients that doesn't send a source name
116         if (!empty($_SERVER['HTTP_USER_AGENT'])) {
117                 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
118                         return "Twidere";
119                 }
120
121                 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
122         } else {
123                 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
124         }
125
126         return "api";
127 }
128
129 /**
130  * Format date for API
131  *
132  * @param string $str Source date, as UTC
133  * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
134  * @throws Exception
135  */
136 function api_date($str)
137 {
138         // Wed May 23 06:01:13 +0000 2007
139         return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
140 }
141
142 /**
143  * Register a function to be the endpoint for defined API path.
144  *
145  * @param string $path   API URL path, relative to DI::baseUrl()
146  * @param string $func   Function name to call on path request
147  * @param bool   $auth   API need logged user
148  * @param string $method HTTP method reqiured to call this endpoint.
149  *                       One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
150  *                       Default to API_METHOD_ANY
151  */
152 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
153 {
154         global $API;
155
156         $API[$path] = [
157                 'func'   => $func,
158                 'auth'   => $auth,
159                 'method' => $method,
160         ];
161
162         // Workaround for hotot
163         $path = str_replace("api/", "api/1.1/", $path);
164
165         $API[$path] = [
166                 'func'   => $func,
167                 'auth'   => $auth,
168                 'method' => $method,
169         ];
170 }
171
172 /**
173  * Check HTTP method of called API
174  *
175  * API endpoints can define which HTTP method to accept when called.
176  * This function check the current HTTP method agains endpoint
177  * registered method.
178  *
179  * @param string $method Required methods, uppercase, separated by comma
180  * @return bool
181  */
182 function api_check_method($method)
183 {
184         if ($method == "*") {
185                 return true;
186         }
187         return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
188 }
189
190 /**
191  * Main API entry point
192  *
193  * Authenticate user, call registered API function, set HTTP headers
194  *
195  * @param App $a App
196  * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
197  * @return string|array API call result
198  * @throws Exception
199  */
200 function api_call(App $a, App\Arguments $args = null)
201 {
202         global $API, $called_api;
203
204         if ($args == null) {
205                 $args = DI::args();
206         }
207
208         $type = "json";
209         if (strpos($args->getCommand(), ".xml") > 0) {
210                 $type = "xml";
211         }
212         if (strpos($args->getCommand(), ".json") > 0) {
213                 $type = "json";
214         }
215         if (strpos($args->getCommand(), ".rss") > 0) {
216                 $type = "rss";
217         }
218         if (strpos($args->getCommand(), ".atom") > 0) {
219                 $type = "atom";
220         }
221
222         try {
223                 foreach ($API as $p => $info) {
224                         if (strpos($args->getCommand(), $p) === 0) {
225                                 if (!api_check_method($info['method'])) {
226                                         throw new MethodNotAllowedException();
227                                 }
228
229                                 $called_api = explode("/", $p);
230
231                                 if (!empty($info['auth']) && api_user() === false) {
232                                         BasicAuth::getCurrentUserID(true);
233                                         Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
234                                 }
235
236                                 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
237
238                                 $stamp =  microtime(true);
239                                 $return = call_user_func($info['func'], $type);
240                                 $duration = floatval(microtime(true) - $stamp);
241
242                                 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
243
244                                 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
245
246                                 if (false === $return) {
247                                         /*
248                                                 * api function returned false withour throw an
249                                                 * exception. This should not happend, throw a 500
250                                                 */
251                                         throw new InternalServerErrorException();
252                                 }
253
254                                 switch ($type) {
255                                         case "xml":
256                                                 header("Content-Type: text/xml");
257                                                 break;
258                                         case "json":
259                                                 header("Content-Type: application/json");
260                                                 if (!empty($return)) {
261                                                         $json = json_encode(end($return));
262                                                         if (!empty($_GET['callback'])) {
263                                                                 $json = $_GET['callback'] . "(" . $json . ")";
264                                                         }
265                                                         $return = $json;
266                                                 }
267                                                 break;
268                                         case "rss":
269                                                 header("Content-Type: application/rss+xml");
270                                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
271                                                 break;
272                                         case "atom":
273                                                 header("Content-Type: application/atom+xml");
274                                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
275                                                 break;
276                                 }
277                                 return $return;
278                         }
279                 }
280
281                 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
282                 throw new NotFoundException();
283         } catch (HTTPException $e) {
284                 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
285         }
286 }
287
288 /**
289  * Set values for RSS template
290  *
291  * @param array $arr       Array to be passed to template
292  * @param array $user_info User info
293  * @return array
294  * @throws BadRequestException
295  * @throws ImagickException
296  * @throws InternalServerErrorException
297  * @throws UnauthorizedException
298  * @todo  find proper type-hints
299  */
300 function api_rss_extra($arr, $user_info)
301 {
302         if (is_null($user_info)) {
303                 $uid = BaseApi::getCurrentUserID();
304                 if (empty($uid)) {
305                         throw new ForbiddenException();
306                 }
307                 
308                 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
309         }
310
311         $arr['$user'] = $user_info;
312         $arr['$rss'] = [
313                 'alternate'    => $user_info['url'],
314                 'self'         => DI::baseUrl() . "/" . DI::args()->getQueryString(),
315                 'base'         => DI::baseUrl(),
316                 'updated'      => api_date(null),
317                 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
318                 'language'     => $user_info['lang'],
319                 'logo'         => DI::baseUrl() . "/images/friendica-32.png",
320         ];
321
322         return $arr;
323 }
324
325
326 /**
327  * Unique contact to contact url.
328  *
329  * @param int $id Contact id
330  * @return bool|string
331  *                Contact url or False if contact id is unknown
332  * @throws Exception
333  */
334 function api_unique_id_to_nurl($id)
335 {
336         $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
337
338         if (DBA::isResult($r)) {
339                 return $r["nurl"];
340         } else {
341                 return false;
342         }
343 }
344
345 /**
346  * Get user info array.
347  *
348  * @param App        $a          App
349  * @param int|string $contact_id Contact ID or URL
350  * @return array|bool
351  * @throws BadRequestException
352  * @throws ImagickException
353  * @throws InternalServerErrorException
354  * @throws UnauthorizedException
355  */
356 function api_get_user($contact_id = null)
357 {
358         global $called_api;
359
360         $user = null;
361         $extra_query = "";
362         $url = "";
363
364         Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
365
366         // Searching for contact URL
367         if (!is_null($contact_id) && (intval($contact_id) == 0)) {
368                 $user = Strings::normaliseLink($contact_id);
369                 $url = $user;
370                 $extra_query = "AND `contact`.`nurl` = ? ";
371                 if (api_user() !== false) {
372                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
373                 }
374         }
375
376         // Searching for contact id with uid = 0
377         if (!is_null($contact_id) && (intval($contact_id) != 0)) {
378                 $user = api_unique_id_to_nurl(intval($contact_id));
379
380                 if ($user == "") {
381                         throw new BadRequestException("User ID ".$contact_id." not found.");
382                 }
383
384                 $url = $user;
385                 $extra_query = "AND `contact`.`nurl` = ? ";
386                 if (api_user() !== false) {
387                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
388                 }
389         }
390
391         if (is_null($user) && !empty($_GET['user_id'])) {
392                 $user = api_unique_id_to_nurl($_GET['user_id']);
393
394                 if ($user == "") {
395                         throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
396                 }
397
398                 $url = $user;
399                 $extra_query = "AND `contact`.`nurl` = ? ";
400                 if (api_user() !== false) {
401                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
402                 }
403         }
404         if (is_null($user) && !empty($_GET['screen_name'])) {
405                 $user = $_GET['screen_name'];
406                 $extra_query = "AND `contact`.`nick` = ? ";
407                 if (api_user() !== false) {
408                         $extra_query .= "AND `contact`.`uid`=".intval(api_user());
409                 }
410         }
411
412         if (is_null($user) && !empty($_GET['profileurl'])) {
413                 $user = Strings::normaliseLink($_GET['profileurl']);
414                 $extra_query = "AND `contact`.`nurl` = ? ";
415                 if (api_user() !== false) {
416                         $extra_query .= "AND `contact`.`uid`=".intval(api_user());
417                 }
418         }
419
420         // $called_api is the API path exploded on / and is expected to have at least 2 elements
421         if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) {
422                 $argid = count($called_api);
423                 if (!empty(DI::args()->getArgv()[$argid])) {
424                         $data = explode(".", DI::args()->getArgv()[$argid]);
425                         if (count($data) > 1) {
426                                 [$user, $null] = $data;
427                         }
428                 }
429                 if (is_numeric($user)) {
430                         $user = api_unique_id_to_nurl(intval($user));
431
432                         if ($user != "") {
433                                 $url = $user;
434                                 $extra_query = "AND `contact`.`nurl` = ? ";
435                                 if (api_user() !== false) {
436                                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
437                                 }
438                         }
439                 } else {
440                         $extra_query = "AND `contact`.`nick` = ? ";
441                         if (api_user() !== false) {
442                                 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
443                         }
444                 }
445         }
446
447         Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
448
449         if (!$user) {
450                 if (api_user() === false) {
451                         BasicAuth::getCurrentUserID(true);
452                         return false;
453                 } else {
454                         $user = api_user();
455                         $extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
456                 }
457         }
458
459         Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
460
461         // user info
462         $uinfo = DBA::toArray(DBA::p(
463                 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
464                         WHERE 1
465                 $extra_query",
466                 $user
467         ));
468
469         if (DBA::isResult($uinfo)) {
470                 // Selecting the id by priority, friendica first
471                 api_best_nickname($uinfo);
472                 return DI::twitterUser()->createFromContactId($uinfo[0]['cid'], $uinfo[0]['uid'])->toArray();
473         }
474
475         if ($url == "") {
476                 throw new BadRequestException("User not found.");
477         }
478
479         $cid = Contact::getIdForURL($url, 0, false);
480
481         if (!empty($cid)) {
482                 return DI::twitterUser()->createFromContactId($cid, 0)->toArray();
483         } else {
484                 throw new BadRequestException("User ".$url." not found.");
485         }
486 }
487
488 /**
489  * return api-formatted array for item's author and owner
490  *
491  * @param App   $a    App
492  * @param array $item item from db
493  * @return array(array:author, array:owner)
494  * @throws BadRequestException
495  * @throws ImagickException
496  * @throws InternalServerErrorException
497  * @throws UnauthorizedException
498  */
499 function api_item_get_user(App $a, $item)
500 {
501         $status_user = DI::twitterUser()->createFromContactId($item['author-id'] ?? null, BaseApi::getCurrentUserID())->toArray();
502
503         $author_user = $status_user;
504
505         $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
506
507         if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
508                 $owner_user = DI::twitterUser()->createFromContactId($item['owner-id'] ?? null, BaseApi::getCurrentUserID())->toArray();
509         } else {
510                 $owner_user = $author_user;
511         }
512
513         return ([$status_user, $author_user, $owner_user]);
514 }
515
516 /**
517  * TWITTER API
518  */
519
520 /**
521  * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
522  * returns a 401 status code and an error message if not.
523  *
524  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
525  *
526  * @param string $type Return type (atom, rss, xml, json)
527  * @return array|string
528  * @throws BadRequestException
529  * @throws ForbiddenException
530  * @throws ImagickException
531  * @throws InternalServerErrorException
532  * @throws UnauthorizedException
533  */
534 function api_account_verify_credentials($type)
535 {
536         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
537
538         unset($_REQUEST["user_id"]);
539         unset($_GET["user_id"]);
540
541         unset($_REQUEST["screen_name"]);
542         unset($_GET["screen_name"]);
543
544         $skip_status = $_REQUEST['skip_status'] ?? false;
545
546         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
547
548         // "verified" isn't used here in the standard
549         unset($user_info["verified"]);
550
551         // - Adding last status
552         if (!$skip_status) {
553                 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
554                 if (!empty($item)) {
555                         $user_info['status'] = api_format_item($item, $type);
556                 }
557         }
558
559         // "uid" and "self" are only needed for some internal stuff, so remove it from here
560         unset($user_info["uid"]);
561         unset($user_info["self"]);
562
563         return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
564 }
565
566 /// @TODO move to top of file or somewhere better
567 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
568
569 /**
570  * Get data from $_POST or $_GET
571  *
572  * @param string $k
573  * @return null
574  */
575 function requestdata($k)
576 {
577         if (!empty($_POST[$k])) {
578                 return $_POST[$k];
579         }
580         if (!empty($_GET[$k])) {
581                 return $_GET[$k];
582         }
583         return null;
584 }
585
586 /**
587  * Deprecated function to upload media.
588  *
589  * @param string $type Return type (atom, rss, xml, json)
590  *
591  * @return array|string
592  * @throws BadRequestException
593  * @throws ForbiddenException
594  * @throws ImagickException
595  * @throws InternalServerErrorException
596  * @throws UnauthorizedException
597  */
598 function api_statuses_mediap($type)
599 {
600         $a = DI::app();
601
602         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
603
604         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
605         
606         $_REQUEST['profile_uid'] = api_user();
607         $_REQUEST['api_source'] = true;
608         $txt = requestdata('status') ?? '';
609         /// @TODO old-lost code?
610         //$txt = urldecode(requestdata('status'));
611
612         if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
613                 $txt = HTML::toBBCodeVideo($txt);
614                 $config = HTMLPurifier_Config::createDefault();
615                 $config->set('Cache.DefinitionImpl', null);
616                 $purifier = new HTMLPurifier($config);
617                 $txt = $purifier->purify($txt);
618         }
619         $txt = HTML::toBBCode($txt);
620
621         DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
622
623         $picture = wall_upload_post($a, false);
624
625         // now that we have the img url in bbcode we can add it to the status and insert the wall item.
626         $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
627         $item_id = item_post($a);
628
629         // output the post that we just posted.
630         return api_status_show($type, $item_id);
631 }
632
633 /// @TODO move this to top of file or somewhere better!
634 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
635
636 /**
637  * Updates the user’s current status.
638  *
639  * @param string $type Return type (atom, rss, xml, json)
640  *
641  * @return array|string
642  * @throws BadRequestException
643  * @throws ForbiddenException
644  * @throws ImagickException
645  * @throws InternalServerErrorException
646  * @throws TooManyRequestsException
647  * @throws UnauthorizedException
648  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
649  */
650 function api_statuses_update($type)
651 {
652         $a = DI::app();
653
654         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
655
656         // convert $_POST array items to the form we use for web posts.
657         if (requestdata('htmlstatus')) {
658                 $txt = requestdata('htmlstatus') ?? '';
659                 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
660                         $txt = HTML::toBBCodeVideo($txt);
661
662                         $config = HTMLPurifier_Config::createDefault();
663                         $config->set('Cache.DefinitionImpl', null);
664
665                         $purifier = new HTMLPurifier($config);
666                         $txt = $purifier->purify($txt);
667
668                         $_REQUEST['body'] = HTML::toBBCode($txt);
669                 }
670         } else {
671                 $_REQUEST['body'] = requestdata('status');
672         }
673
674         $_REQUEST['title'] = requestdata('title');
675
676         $parent = requestdata('in_reply_to_status_id');
677
678         // Twidere sends "-1" if it is no reply ...
679         if ($parent == -1) {
680                 $parent = "";
681         }
682
683         if (ctype_digit($parent)) {
684                 $_REQUEST['parent'] = $parent;
685         } else {
686                 $_REQUEST['parent_uri'] = $parent;
687         }
688
689         if (requestdata('lat') && requestdata('long')) {
690                 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
691         }
692         $_REQUEST['profile_uid'] = api_user();
693
694         if (!$parent) {
695                 // Check for throttling (maximum posts per day, week and month)
696                 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
697                 if ($throttle_day > 0) {
698                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
699
700                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
701                         $posts_day = Post::count($condition);
702
703                         if ($posts_day > $throttle_day) {
704                                 logger::info('Daily posting limit reached for user '.api_user());
705                                 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
706                                 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));
707                         }
708                 }
709
710                 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
711                 if ($throttle_week > 0) {
712                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
713
714                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
715                         $posts_week = Post::count($condition);
716
717                         if ($posts_week > $throttle_week) {
718                                 logger::info('Weekly posting limit reached for user '.api_user());
719                                 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
720                                 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));
721                         }
722                 }
723
724                 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
725                 if ($throttle_month > 0) {
726                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
727
728                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
729                         $posts_month = Post::count($condition);
730
731                         if ($posts_month > $throttle_month) {
732                                 logger::info('Monthly posting limit reached for user '.api_user());
733                                 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
734                                 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));
735                         }
736                 }
737         }
738
739         if (requestdata('media_ids')) {
740                 $ids = explode(',', requestdata('media_ids') ?? '');
741         } elseif (!empty($_FILES['media'])) {
742                 // upload the image if we have one
743                 $picture = wall_upload_post($a, false);
744                 if (is_array($picture)) {
745                         $ids[] = $picture['id'];
746                 }
747         }
748
749         $attachments = [];
750         $ressources = [];
751
752         if (!empty($ids)) {
753                 foreach ($ids as $id) {
754                         $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
755                                         INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
756                                                 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
757                                         ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
758
759                         if (!empty($media)) {
760                                 $ressources[] = $media[0]['resource-id'];
761                                 $phototypes = Images::supportedTypes();
762                                 $ext = $phototypes[$media[0]['type']];
763
764                                 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
765                                         'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
766                                         'size' => $media[0]['datasize'],
767                                         'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
768                                         'description' => $media[0]['desc'] ?? '',
769                                         'width' => $media[0]['width'],
770                                         'height' => $media[0]['height']];
771
772                                 if (count($media) > 1) {
773                                         $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
774                                         $attachment['preview-width'] = $media[1]['width'];
775                                         $attachment['preview-height'] = $media[1]['height'];
776                                 }
777                                 $attachments[] = $attachment;
778                         }
779                 }
780
781                 // We have to avoid that the post is rejected because of an empty body
782                 if (empty($_REQUEST['body'])) {
783                         $_REQUEST['body'] = '[hr]';
784                 }
785         }
786
787         if (!empty($attachments)) {
788                 $_REQUEST['attachments'] = $attachments;
789         }
790
791         // set this so that the item_post() function is quiet and doesn't redirect or emit json
792
793         $_REQUEST['api_source'] = true;
794
795         if (empty($_REQUEST['source'])) {
796                 $_REQUEST["source"] = api_source();
797         }
798
799         // call out normal post function
800         $item_id = item_post($a);
801
802         if (!empty($ressources) && !empty($item_id)) {
803                 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
804                 foreach ($ressources as $ressource) {
805                         Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
806                 }
807         }
808
809         // output the post that we just posted.
810         return api_status_show($type, $item_id);
811 }
812
813 /// @TODO move to top of file or somewhere better
814 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
815 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
816
817 /**
818  * Uploads an image to Friendica.
819  *
820  * @return array
821  * @throws BadRequestException
822  * @throws ForbiddenException
823  * @throws ImagickException
824  * @throws InternalServerErrorException
825  * @throws UnauthorizedException
826  * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
827  */
828 function api_media_upload()
829 {
830         $a = DI::app();
831
832         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
833
834         if (empty($_FILES['media'])) {
835                 // Output error
836                 throw new BadRequestException("No media.");
837         }
838
839         $media = wall_upload_post($a, false);
840         if (!$media) {
841                 // Output error
842                 throw new InternalServerErrorException();
843         }
844
845         $returndata = [];
846         $returndata["media_id"] = $media["id"];
847         $returndata["media_id_string"] = (string)$media["id"];
848         $returndata["size"] = $media["size"];
849         $returndata["image"] = ["w" => $media["width"],
850                                 "h" => $media["height"],
851                                 "image_type" => $media["type"],
852                                 "friendica_preview_url" => $media["preview"]];
853
854         Logger::info('Media uploaded', ['return' => $returndata]);
855
856         return ["media" => $returndata];
857 }
858
859 /// @TODO move to top of file or somewhere better
860 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
861
862 /**
863  * Updates media meta data (picture descriptions)
864  *
865  * @param string $type Return type (atom, rss, xml, json)
866  *
867  * @return array|string
868  * @throws BadRequestException
869  * @throws ForbiddenException
870  * @throws ImagickException
871  * @throws InternalServerErrorException
872  * @throws TooManyRequestsException
873  * @throws UnauthorizedException
874  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
875  *
876  * @todo Compare the corresponding Twitter function for correct return values
877  */
878 function api_media_metadata_create($type)
879 {
880         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
881
882         $postdata = Network::postdata();
883
884         if (empty($postdata)) {
885                 throw new BadRequestException("No post data");
886         }
887
888         $data = json_decode($postdata, true);
889         if (empty($data)) {
890                 throw new BadRequestException("Invalid post data");
891         }
892
893         if (empty($data['media_id']) || empty($data['alt_text'])) {
894                 throw new BadRequestException("Missing post data values");
895         }
896
897         if (empty($data['alt_text']['text'])) {
898                 throw new BadRequestException("No alt text.");
899         }
900
901         Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
902
903         $condition =  ['id' => $data['media_id'], 'uid' => api_user()];
904         $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
905         if (!DBA::isResult($photo)) {
906                 throw new BadRequestException("Metadata not found.");
907         }
908
909         DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
910 }
911
912 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
913
914 /**
915  * @param string $type    Return format (atom, rss, xml, json)
916  * @param int    $item_id
917  * @return array|string
918  * @throws Exception
919  */
920 function api_status_show($type, $item_id)
921 {
922         Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
923
924         $status_info = [];
925
926         $item = api_get_item(['id' => $item_id]);
927         if (!empty($item)) {
928                 $status_info = api_format_item($item, $type);
929         }
930
931         Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
932
933         return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
934 }
935
936 /**
937  * Retrieves the last public status of the provided user info
938  *
939  * @param int    $ownerId Public contact Id
940  * @param int    $uid     User Id
941  * @return array
942  * @throws Exception
943  */
944 function api_get_last_status($ownerId, $uid)
945 {
946         $condition = [
947                 'author-id'=> $ownerId,
948                 'uid'      => $uid,
949                 'gravity'  => [GRAVITY_PARENT, GRAVITY_COMMENT],
950                 'private'  => [Item::PUBLIC, Item::UNLISTED]
951         ];
952
953         $item = api_get_item($condition);
954
955         return $item;
956 }
957
958 /**
959  * Retrieves a single item record based on the provided condition and converts it for API use.
960  *
961  * @param array $condition Item table condition array
962  * @return array
963  * @throws Exception
964  */
965 function api_get_item(array $condition)
966 {
967         $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
968
969         return $item;
970 }
971
972 /**
973  * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
974  * The author's most recent status will be returned inline.
975  *
976  * @param string $type Return type (atom, rss, xml, json)
977  * @return array|string
978  * @throws BadRequestException
979  * @throws ImagickException
980  * @throws InternalServerErrorException
981  * @throws UnauthorizedException
982  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
983  */
984 function api_users_show($type)
985 {
986         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
987
988         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
989
990         $item = api_get_last_status($user_info['pid'], $user_info['uid']);
991         if (!empty($item)) {
992                 $user_info['status'] = api_format_item($item, $type);
993         }
994
995         // "uid" and "self" are only needed for some internal stuff, so remove it from here
996         unset($user_info['uid']);
997         unset($user_info['self']);
998
999         return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
1000 }
1001
1002 /// @TODO move to top of file or somewhere better
1003 api_register_func('api/users/show', 'api_users_show');
1004 api_register_func('api/externalprofile/show', 'api_users_show');
1005
1006 /**
1007  * Search a public user account.
1008  *
1009  * @param string $type Return type (atom, rss, xml, json)
1010  *
1011  * @return array|string
1012  * @throws BadRequestException
1013  * @throws ImagickException
1014  * @throws InternalServerErrorException
1015  * @throws UnauthorizedException
1016  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1017  */
1018 function api_users_search($type)
1019 {
1020         $userlist = [];
1021
1022         if (!empty($_GET['q'])) {
1023                 $contacts = Contact::selectToArray(
1024                         ['id'],
1025                         [
1026                                 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1027                                 $_GET['q'],
1028                                 $_GET['q'],
1029                                 $_GET['q'],
1030                                 $_GET['q'],
1031                         ]
1032                 );
1033
1034                 if (DBA::isResult($contacts)) {
1035                         $k = 0;
1036                         foreach ($contacts as $contact) {
1037                                 $user_info = DI::twitterUser()->createFromContactId($contact['id'], BaseApi::getCurrentUserID())->toArray();
1038
1039                                 if ($type == 'xml') {
1040                                         $userlist[$k++ . ':user'] = $user_info;
1041                                 } else {
1042                                         $userlist[] = $user_info;
1043                                 }
1044                         }
1045                         $userlist = ['users' => $userlist];
1046                 } else {
1047                         throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1048                 }
1049         } else {
1050                 throw new BadRequestException('No search term specified.');
1051         }
1052
1053         return DI::apiResponse()->formatData('users', $type, $userlist);
1054 }
1055
1056 /// @TODO move to top of file or somewhere better
1057 api_register_func('api/users/search', 'api_users_search');
1058
1059 /**
1060  * Return user objects
1061  *
1062  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1063  *
1064  * @param string $type Return format: json or xml
1065  *
1066  * @return array|string
1067  * @throws BadRequestException
1068  * @throws ImagickException
1069  * @throws InternalServerErrorException
1070  * @throws NotFoundException if the results are empty.
1071  * @throws UnauthorizedException
1072  */
1073 function api_users_lookup($type)
1074 {
1075         $users = [];
1076
1077         if (!empty($_REQUEST['user_id'])) {
1078                 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1079                         if (!empty($id)) {
1080                                 $users[] = api_get_user($id);
1081                         }
1082                 }
1083         }
1084
1085         if (empty($users)) {
1086                 throw new NotFoundException;
1087         }
1088
1089         return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
1090 }
1091
1092 /// @TODO move to top of file or somewhere better
1093 api_register_func('api/users/lookup', 'api_users_lookup', true);
1094
1095 /**
1096  * Returns statuses that match a specified query.
1097  *
1098  * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1099  *
1100  * @param string $type Return format: json, xml, atom, rss
1101  *
1102  * @return array|string
1103  * @throws BadRequestException if the "q" parameter is missing.
1104  * @throws ForbiddenException
1105  * @throws ImagickException
1106  * @throws InternalServerErrorException
1107  * @throws UnauthorizedException
1108  */
1109 function api_search($type)
1110 {
1111         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1112
1113         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1114
1115         if (empty($_REQUEST['q'])) {
1116                 throw new BadRequestException('q parameter is required.');
1117         }
1118
1119         $searchTerm = trim(rawurldecode($_REQUEST['q']));
1120
1121         $data = [];
1122         $data['status'] = [];
1123         $count = 15;
1124         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1125         if (!empty($_REQUEST['rpp'])) {
1126                 $count = $_REQUEST['rpp'];
1127         } elseif (!empty($_REQUEST['count'])) {
1128                 $count = $_REQUEST['count'];
1129         }
1130
1131         $since_id = $_REQUEST['since_id'] ?? 0;
1132         $max_id = $_REQUEST['max_id'] ?? 0;
1133         $page = $_REQUEST['page'] ?? 1;
1134
1135         $start = max(0, ($page - 1) * $count);
1136
1137         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1138         if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1139                 $searchTerm = $matches[1];
1140                 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1141                 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1142                 $uriids = [];
1143                 while ($tag = DBA::fetch($tags)) {
1144                         $uriids[] = $tag['uri-id'];
1145                 }
1146                 DBA::close($tags);
1147
1148                 if (empty($uriids)) {
1149                         return DI::apiResponse()->formatData('statuses', $type, $data);
1150                 }
1151
1152                 $condition = ['uri-id' => $uriids];
1153                 if ($exclude_replies) {
1154                         $condition['gravity'] = GRAVITY_PARENT;
1155                 }
1156
1157                 $params['group_by'] = ['uri-id'];
1158         } else {
1159                 $condition = ["`id` > ?
1160                         " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1161                         AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1162                         AND `body` LIKE CONCAT('%',?,'%')",
1163                         $since_id, api_user(), $_REQUEST['q']];
1164                 if ($max_id > 0) {
1165                         $condition[0] .= ' AND `id` <= ?';
1166                         $condition[] = $max_id;
1167                 }
1168         }
1169
1170         $statuses = [];
1171
1172         if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1173                 $id = Item::fetchByLink($searchTerm, api_user());
1174                 if (!$id) {
1175                         // Public post
1176                         $id = Item::fetchByLink($searchTerm);
1177                 }
1178
1179                 if (!empty($id)) {
1180                         $statuses = Post::select([], ['id' => $id]);
1181                 }
1182         }
1183
1184         $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1185
1186         $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1187
1188         bindComments($data['status']);
1189
1190         return DI::apiResponse()->formatData('statuses', $type, $data);
1191 }
1192
1193 /// @TODO move to top of file or somewhere better
1194 api_register_func('api/search/tweets', 'api_search', true);
1195 api_register_func('api/search', 'api_search', true);
1196
1197 /**
1198  * Returns the most recent statuses posted by the user and the users they follow.
1199  *
1200  * @see  https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1201  *
1202  * @param string $type Return type (atom, rss, xml, json)
1203  *
1204  * @return array|string
1205  * @throws BadRequestException
1206  * @throws ForbiddenException
1207  * @throws ImagickException
1208  * @throws InternalServerErrorException
1209  * @throws UnauthorizedException
1210  * @todo Optional parameters
1211  * @todo Add reply info
1212  */
1213 function api_statuses_home_timeline($type)
1214 {
1215         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1216         
1217         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1218
1219         unset($_REQUEST["user_id"]);
1220         unset($_GET["user_id"]);
1221
1222         unset($_REQUEST["screen_name"]);
1223         unset($_GET["screen_name"]);
1224
1225         // get last network messages
1226
1227         // params
1228         $count = $_REQUEST['count'] ?? 20;
1229         $page = $_REQUEST['page']?? 0;
1230         $since_id = $_REQUEST['since_id'] ?? 0;
1231         $max_id = $_REQUEST['max_id'] ?? 0;
1232         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1233         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1234
1235         $start = max(0, ($page - 1) * $count);
1236
1237         $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1238                 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1239
1240         if ($max_id > 0) {
1241                 $condition[0] .= " AND `id` <= ?";
1242                 $condition[] = $max_id;
1243         }
1244         if ($exclude_replies) {
1245                 $condition[0] .= ' AND `gravity` = ?';
1246                 $condition[] = GRAVITY_PARENT;
1247         }
1248         if ($conversation_id > 0) {
1249                 $condition[0] .= " AND `parent` = ?";
1250                 $condition[] = $conversation_id;
1251         }
1252
1253         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1254         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1255
1256         $items = Post::toArray($statuses);
1257
1258         $ret = api_format_items($items, $user_info, false, $type);
1259
1260         // Set all posts from the query above to seen
1261         $idarray = [];
1262         foreach ($items as $item) {
1263                 $idarray[] = intval($item["id"]);
1264         }
1265
1266         if (!empty($idarray)) {
1267                 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1268                 if ($unseen) {
1269                         Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1270                 }
1271         }
1272
1273         bindComments($ret);
1274
1275         $data = ['status' => $ret];
1276         switch ($type) {
1277                 case "atom":
1278                         break;
1279                 case "rss":
1280                         $data = api_rss_extra($data, $user_info);
1281                         break;
1282         }
1283
1284         return DI::apiResponse()->formatData("statuses", $type, $data);
1285 }
1286
1287
1288 /// @TODO move to top of file or somewhere better
1289 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1290 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1291
1292 /**
1293  * Returns the most recent statuses from public users.
1294  *
1295  * @param string $type Return type (atom, rss, xml, json)
1296  *
1297  * @return array|string
1298  * @throws BadRequestException
1299  * @throws ForbiddenException
1300  * @throws ImagickException
1301  * @throws InternalServerErrorException
1302  * @throws UnauthorizedException
1303  */
1304 function api_statuses_public_timeline($type)
1305 {
1306         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1307
1308         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1309
1310         // get last network messages
1311
1312         // params
1313         $count = $_REQUEST['count'] ?? 20;
1314         $page = $_REQUEST['page'] ?? 1;
1315         $since_id = $_REQUEST['since_id'] ?? 0;
1316         $max_id = $_REQUEST['max_id'] ?? 0;
1317         $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1318         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1319
1320         $start = max(0, ($page - 1) * $count);
1321
1322         if ($exclude_replies && !$conversation_id) {
1323                 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1324                         GRAVITY_PARENT, $since_id, Item::PUBLIC];
1325
1326                 if ($max_id > 0) {
1327                         $condition[0] .= " AND `id` <= ?";
1328                         $condition[] = $max_id;
1329                 }
1330
1331                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1332                 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1333
1334                 $r = Post::toArray($statuses);
1335         } else {
1336                 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1337                         GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1338
1339                 if ($max_id > 0) {
1340                         $condition[0] .= " AND `id` <= ?";
1341                         $condition[] = $max_id;
1342                 }
1343                 if ($conversation_id > 0) {
1344                         $condition[0] .= " AND `parent` = ?";
1345                         $condition[] = $conversation_id;
1346                 }
1347
1348                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1349                 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1350
1351                 $r = Post::toArray($statuses);
1352         }
1353
1354         $ret = api_format_items($r, $user_info, false, $type);
1355
1356         bindComments($ret);
1357
1358         $data = ['status' => $ret];
1359         switch ($type) {
1360                 case "atom":
1361                         break;
1362                 case "rss":
1363                         $data = api_rss_extra($data, $user_info);
1364                         break;
1365         }
1366
1367         return DI::apiResponse()->formatData("statuses", $type, $data);
1368 }
1369
1370 /// @TODO move to top of file or somewhere better
1371 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1372
1373 /**
1374  * Returns the most recent statuses posted by users this node knows about.
1375  *
1376  * @param string $type Return format: json, xml, atom, rss
1377  * @return array|string
1378  * @throws BadRequestException
1379  * @throws ForbiddenException
1380  * @throws ImagickException
1381  * @throws InternalServerErrorException
1382  * @throws UnauthorizedException
1383  */
1384 function api_statuses_networkpublic_timeline($type)
1385 {
1386         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1387
1388         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1389
1390         $since_id        = $_REQUEST['since_id'] ?? 0;
1391         $max_id          = $_REQUEST['max_id'] ?? 0;
1392
1393         // pagination
1394         $count = $_REQUEST['count'] ?? 20;
1395         $page  = $_REQUEST['page'] ?? 1;
1396
1397         $start = max(0, ($page - 1) * $count);
1398
1399         $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1400                 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1401
1402         if ($max_id > 0) {
1403                 $condition[0] .= " AND `id` <= ?";
1404                 $condition[] = $max_id;
1405         }
1406
1407         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1408         $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1409
1410         $ret = api_format_items($statuses, $user_info, false, $type);
1411
1412         bindComments($ret);
1413
1414         $data = ['status' => $ret];
1415         switch ($type) {
1416                 case "atom":
1417                         break;
1418                 case "rss":
1419                         $data = api_rss_extra($data, $user_info);
1420                         break;
1421         }
1422
1423         return DI::apiResponse()->formatData("statuses", $type, $data);
1424 }
1425
1426 /// @TODO move to top of file or somewhere better
1427 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1428
1429 /**
1430  * Returns a single status.
1431  *
1432  * @param string $type Return type (atom, rss, xml, json)
1433  *
1434  * @return array|string
1435  * @throws BadRequestException
1436  * @throws ForbiddenException
1437  * @throws ImagickException
1438  * @throws InternalServerErrorException
1439  * @throws UnauthorizedException
1440  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1441  */
1442 function api_statuses_show($type)
1443 {
1444         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1445
1446         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1447
1448         // params
1449         $id = intval(DI::args()->getArgv()[3] ?? 0);
1450
1451         if ($id == 0) {
1452                 $id = intval($_REQUEST['id'] ?? 0);
1453         }
1454
1455         // Hotot workaround
1456         if ($id == 0) {
1457                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1458         }
1459
1460         logger::notice('API: api_statuses_show: ' . $id);
1461
1462         $conversation = !empty($_REQUEST['conversation']);
1463
1464         // try to fetch the item for the local user - or the public item, if there is no local one
1465         $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1466         if (!DBA::isResult($uri_item)) {
1467                 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1468         }
1469
1470         $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1471         if (!DBA::isResult($item)) {
1472                 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1473         }
1474
1475         $id = $item['id'];
1476
1477         if ($conversation) {
1478                 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1479                 $params = ['order' => ['id' => true]];
1480         } else {
1481                 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1482                 $params = [];
1483         }
1484
1485         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1486
1487         /// @TODO How about copying this to above methods which don't check $r ?
1488         if (!DBA::isResult($statuses)) {
1489                 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1490         }
1491
1492         $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1493
1494         if ($conversation) {
1495                 $data = ['status' => $ret];
1496                 return DI::apiResponse()->formatData("statuses", $type, $data);
1497         } else {
1498                 $data = ['status' => $ret[0]];
1499                 return DI::apiResponse()->formatData("status", $type, $data);
1500         }
1501 }
1502
1503 /// @TODO move to top of file or somewhere better
1504 api_register_func('api/statuses/show', 'api_statuses_show', true);
1505
1506 /**
1507  *
1508  * @param string $type Return type (atom, rss, xml, json)
1509  *
1510  * @return array|string
1511  * @throws BadRequestException
1512  * @throws ForbiddenException
1513  * @throws ImagickException
1514  * @throws InternalServerErrorException
1515  * @throws UnauthorizedException
1516  * @todo nothing to say?
1517  */
1518 function api_conversation_show($type)
1519 {
1520         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1521
1522         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1523
1524         // params
1525         $id       = intval(DI::args()->getArgv()[3]           ?? 0);
1526         $since_id = intval($_REQUEST['since_id'] ?? 0);
1527         $max_id   = intval($_REQUEST['max_id']   ?? 0);
1528         $count    = intval($_REQUEST['count']    ?? 20);
1529         $page     = intval($_REQUEST['page']     ?? 1);
1530
1531         $start = max(0, ($page - 1) * $count);
1532
1533         if ($id == 0) {
1534                 $id = intval($_REQUEST['id'] ?? 0);
1535         }
1536
1537         // Hotot workaround
1538         if ($id == 0) {
1539                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1540         }
1541
1542         Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1543
1544         // try to fetch the item for the local user - or the public item, if there is no local one
1545         $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1546         if (!DBA::isResult($item)) {
1547                 throw new BadRequestException("There is no status with the id $id.");
1548         }
1549
1550         $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1551         if (!DBA::isResult($parent)) {
1552                 throw new BadRequestException("There is no status with this id.");
1553         }
1554
1555         $id = $parent['id'];
1556
1557         $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1558                 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1559
1560         if ($max_id > 0) {
1561                 $condition[0] .= " AND `id` <= ?";
1562                 $condition[] = $max_id;
1563         }
1564
1565         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1566         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1567
1568         if (!DBA::isResult($statuses)) {
1569                 throw new BadRequestException("There is no status with id $id.");
1570         }
1571
1572         $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1573
1574         $data = ['status' => $ret];
1575         return DI::apiResponse()->formatData("statuses", $type, $data);
1576 }
1577
1578 /// @TODO move to top of file or somewhere better
1579 api_register_func('api/conversation/show', 'api_conversation_show', true);
1580 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1581
1582 /**
1583  * Repeats a status.
1584  *
1585  * @param string $type Return type (atom, rss, xml, json)
1586  *
1587  * @return array|string
1588  * @throws BadRequestException
1589  * @throws ForbiddenException
1590  * @throws ImagickException
1591  * @throws InternalServerErrorException
1592  * @throws UnauthorizedException
1593  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1594  */
1595 function api_statuses_repeat($type)
1596 {
1597         global $called_api;
1598
1599         $a = DI::app();
1600
1601         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1602
1603         // params
1604         $id = intval(DI::args()->getArgv()[3] ?? 0);
1605
1606         if ($id == 0) {
1607                 $id = intval($_REQUEST['id'] ?? 0);
1608         }
1609
1610         // Hotot workaround
1611         if ($id == 0) {
1612                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1613         }
1614
1615         logger::notice('API: api_statuses_repeat: ' . $id);
1616
1617         $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1618         $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1619
1620         if (DBA::isResult($item) && !empty($item['body'])) {
1621                 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1622                         if (!Item::performActivity($id, 'announce', local_user())) {
1623                                 throw new InternalServerErrorException();
1624                         }
1625
1626                         $item_id = $id;
1627                 } else {
1628                         if (strpos($item['body'], "[/share]") !== false) {
1629                                 $pos = strpos($item['body'], "[share");
1630                                 $post = substr($item['body'], $pos);
1631                         } else {
1632                                 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1633
1634                                 if (!empty($item['title'])) {
1635                                         $post .= '[h3]' . $item['title'] . "[/h3]\n";
1636                                 }
1637
1638                                 $post .= $item['body'];
1639                                 $post .= "[/share]";
1640                         }
1641                         $_REQUEST['body'] = $post;
1642                         $_REQUEST['profile_uid'] = api_user();
1643                         $_REQUEST['api_source'] = true;
1644
1645                         if (empty($_REQUEST['source'])) {
1646                                 $_REQUEST["source"] = api_source();
1647                         }
1648
1649                         $item_id = item_post($a);
1650                 }
1651         } else {
1652                 throw new ForbiddenException();
1653         }
1654
1655         // output the post that we just posted.
1656         $called_api = [];
1657         return api_status_show($type, $item_id);
1658 }
1659
1660 /// @TODO move to top of file or somewhere better
1661 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1662
1663 /**
1664  * Destroys a specific status.
1665  *
1666  * @param string $type Return type (atom, rss, xml, json)
1667  *
1668  * @return array|string
1669  * @throws BadRequestException
1670  * @throws ForbiddenException
1671  * @throws ImagickException
1672  * @throws InternalServerErrorException
1673  * @throws UnauthorizedException
1674  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1675  */
1676 function api_statuses_destroy($type)
1677 {
1678         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1679
1680         // params
1681         $id = intval(DI::args()->getArgv()[3] ?? 0);
1682
1683         if ($id == 0) {
1684                 $id = intval($_REQUEST['id'] ?? 0);
1685         }
1686
1687         // Hotot workaround
1688         if ($id == 0) {
1689                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1690         }
1691
1692         logger::notice('API: api_statuses_destroy: ' . $id);
1693
1694         $ret = api_statuses_show($type);
1695
1696         Item::deleteForUser(['id' => $id], api_user());
1697
1698         return $ret;
1699 }
1700
1701 /// @TODO move to top of file or somewhere better
1702 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1703
1704 /**
1705  * Returns the most recent mentions.
1706  *
1707  * @param string $type Return type (atom, rss, xml, json)
1708  *
1709  * @return array|string
1710  * @throws BadRequestException
1711  * @throws ForbiddenException
1712  * @throws ImagickException
1713  * @throws InternalServerErrorException
1714  * @throws UnauthorizedException
1715  * @see http://developer.twitter.com/doc/get/statuses/mentions
1716  */
1717 function api_statuses_mentions($type)
1718 {
1719         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1720
1721         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1722
1723         unset($_REQUEST["user_id"]);
1724         unset($_GET["user_id"]);
1725
1726         unset($_REQUEST["screen_name"]);
1727         unset($_GET["screen_name"]);
1728
1729         // get last network messages
1730
1731         // params
1732         $since_id = intval($_REQUEST['since_id'] ?? 0);
1733         $max_id   = intval($_REQUEST['max_id']   ?? 0);
1734         $count    = intval($_REQUEST['count']    ?? 20);
1735         $page     = intval($_REQUEST['page']     ?? 1);
1736
1737         $start = max(0, ($page - 1) * $count);
1738
1739         $query = "`gravity` IN (?, ?) AND `uri-id` IN
1740                 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1741                 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1742
1743         $condition = [
1744                 GRAVITY_PARENT, GRAVITY_COMMENT,
1745                 api_user(),
1746                 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1747                 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1748                 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1749                 api_user(), $since_id,
1750         ];
1751
1752         if ($max_id > 0) {
1753                 $query .= " AND `id` <= ?";
1754                 $condition[] = $max_id;
1755         }
1756
1757         array_unshift($condition, $query);
1758
1759         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1760         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1761
1762         $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1763
1764         $data = ['status' => $ret];
1765         switch ($type) {
1766                 case "atom":
1767                         break;
1768                 case "rss":
1769                         $data = api_rss_extra($data, $user_info);
1770                         break;
1771         }
1772
1773         return DI::apiResponse()->formatData("statuses", $type, $data);
1774 }
1775
1776 /// @TODO move to top of file or somewhere better
1777 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1778 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1779
1780 /**
1781  * Returns the most recent statuses posted by the user.
1782  *
1783  * @param string $type Either "json" or "xml"
1784  * @return string|array
1785  * @throws BadRequestException
1786  * @throws ForbiddenException
1787  * @throws ImagickException
1788  * @throws InternalServerErrorException
1789  * @throws UnauthorizedException
1790  * @see   https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1791  */
1792 function api_statuses_user_timeline($type)
1793 {
1794         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1795
1796         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1797
1798         Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
1799
1800         $since_id        = $_REQUEST['since_id'] ?? 0;
1801         $max_id          = $_REQUEST['max_id'] ?? 0;
1802         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1803         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1804
1805         // pagination
1806         $count = $_REQUEST['count'] ?? 20;
1807         $page  = $_REQUEST['page'] ?? 1;
1808
1809         $start = max(0, ($page - 1) * $count);
1810
1811         $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
1812                 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
1813
1814         if ($user_info['self'] == 1) {
1815                 $condition[0] .= ' AND `wall` ';
1816         }
1817
1818         if ($exclude_replies) {
1819                 $condition[0] .= ' AND `gravity` = ?';
1820                 $condition[] = GRAVITY_PARENT;
1821         }
1822
1823         if ($conversation_id > 0) {
1824                 $condition[0] .= " AND `parent` = ?";
1825                 $condition[] = $conversation_id;
1826         }
1827
1828         if ($max_id > 0) {
1829                 $condition[0] .= " AND `id` <= ?";
1830                 $condition[] = $max_id;
1831         }
1832         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1833         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1834
1835         $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
1836
1837         bindComments($ret);
1838
1839         $data = ['status' => $ret];
1840         switch ($type) {
1841                 case "atom":
1842                         break;
1843                 case "rss":
1844                         $data = api_rss_extra($data, $user_info);
1845                         break;
1846         }
1847
1848         return DI::apiResponse()->formatData("statuses", $type, $data);
1849 }
1850
1851 /// @TODO move to top of file or somewhere better
1852 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1853
1854 /**
1855  * Star/unstar an item.
1856  * param: id : id of the item
1857  *
1858  * @param string $type Return type (atom, rss, xml, json)
1859  *
1860  * @return array|string
1861  * @throws BadRequestException
1862  * @throws ForbiddenException
1863  * @throws ImagickException
1864  * @throws InternalServerErrorException
1865  * @throws UnauthorizedException
1866  * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1867  */
1868 function api_favorites_create_destroy($type)
1869 {
1870         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1871
1872         // for versioned api.
1873         /// @TODO We need a better global soluton
1874         $action_argv_id = 2;
1875         if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1876                 $action_argv_id = 3;
1877         }
1878
1879         if (DI::args()->getArgc() <= $action_argv_id) {
1880                 throw new BadRequestException("Invalid request.");
1881         }
1882         $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1883         if (DI::args()->getArgc() == $action_argv_id + 2) {
1884                 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1885         } else {
1886                 $itemid = intval($_REQUEST['id'] ?? 0);
1887         }
1888
1889         $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
1890
1891         if (!DBA::isResult($item)) {
1892                 throw new BadRequestException("Invalid item.");
1893         }
1894
1895         switch ($action) {
1896                 case "create":
1897                         $item['starred'] = 1;
1898                         break;
1899                 case "destroy":
1900                         $item['starred'] = 0;
1901                         break;
1902                 default:
1903                         throw new BadRequestException("Invalid action ".$action);
1904         }
1905
1906         $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1907
1908         if ($r === false) {
1909                 throw new InternalServerErrorException("DB error");
1910         }
1911
1912         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1913         $rets = api_format_items([$item], $user_info, false, $type);
1914         $ret = $rets[0];
1915
1916         $data = ['status' => $ret];
1917         switch ($type) {
1918                 case "atom":
1919                         break;
1920                 case "rss":
1921                         $data = api_rss_extra($data, $user_info);
1922                         break;
1923         }
1924
1925         return DI::apiResponse()->formatData("status", $type, $data);
1926 }
1927
1928 /// @TODO move to top of file or somewhere better
1929 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1930 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1931
1932 /**
1933  * Returns the most recent favorite statuses.
1934  *
1935  * @param string $type Return type (atom, rss, xml, json)
1936  *
1937  * @return string|array
1938  * @throws BadRequestException
1939  * @throws ForbiddenException
1940  * @throws ImagickException
1941  * @throws InternalServerErrorException
1942  * @throws UnauthorizedException
1943  */
1944 function api_favorites($type)
1945 {
1946         global $called_api;
1947
1948         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1949
1950         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1951
1952         $called_api = [];
1953
1954         // in friendica starred item are private
1955         // return favorites only for self
1956         Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
1957
1958         if ($user_info['self'] == 0) {
1959                 $ret = [];
1960         } else {
1961                 // params
1962                 $since_id = $_REQUEST['since_id'] ?? 0;
1963                 $max_id = $_REQUEST['max_id'] ?? 0;
1964                 $count = $_GET['count'] ?? 20;
1965                 $page = $_REQUEST['page'] ?? 1;
1966
1967                 $start = max(0, ($page - 1) * $count);
1968
1969                 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
1970                         api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1971
1972                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1973
1974                 if ($max_id > 0) {
1975                         $condition[0] .= " AND `id` <= ?";
1976                         $condition[] = $max_id;
1977                 }
1978
1979                 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1980
1981                 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1982         }
1983
1984         bindComments($ret);
1985
1986         $data = ['status' => $ret];
1987         switch ($type) {
1988                 case "atom":
1989                         break;
1990                 case "rss":
1991                         $data = api_rss_extra($data, $user_info);
1992                         break;
1993         }
1994
1995         return DI::apiResponse()->formatData("statuses", $type, $data);
1996 }
1997
1998 /// @TODO move to top of file or somewhere better
1999 api_register_func('api/favorites', 'api_favorites', true);
2000
2001 /**
2002  *
2003  * @param array $item
2004  * @param array $recipient
2005  * @param array $sender
2006  *
2007  * @return array
2008  * @throws InternalServerErrorException
2009  */
2010 function api_format_messages($item, $recipient, $sender)
2011 {
2012         // standard meta information
2013         $ret = [
2014                 'id'                    => $item['id'],
2015                 'sender_id'             => $sender['id'],
2016                 'text'                  => "",
2017                 'recipient_id'          => $recipient['id'],
2018                 'created_at'            => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2019                 'sender_screen_name'    => $sender['screen_name'],
2020                 'recipient_screen_name' => $recipient['screen_name'],
2021                 'sender'                => $sender,
2022                 'recipient'             => $recipient,
2023                 'title'                 => "",
2024                 'friendica_seen'        => $item['seen'] ?? 0,
2025                 'friendica_parent_uri'  => $item['parent-uri'] ?? '',
2026         ];
2027
2028         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2029         if (isset($ret['sender']['uid'])) {
2030                 unset($ret['sender']['uid']);
2031         }
2032         if (isset($ret['sender']['self'])) {
2033                 unset($ret['sender']['self']);
2034         }
2035         if (isset($ret['recipient']['uid'])) {
2036                 unset($ret['recipient']['uid']);
2037         }
2038         if (isset($ret['recipient']['self'])) {
2039                 unset($ret['recipient']['self']);
2040         }
2041
2042         //don't send title to regular StatusNET requests to avoid confusing these apps
2043         if (!empty($_GET['getText'])) {
2044                 $ret['title'] = $item['title'];
2045                 if ($_GET['getText'] == 'html') {
2046                         $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
2047                 } elseif ($_GET['getText'] == 'plain') {
2048                         $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
2049                 }
2050         } else {
2051                 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
2052         }
2053         if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2054                 unset($ret['sender']);
2055                 unset($ret['recipient']);
2056         }
2057
2058         return $ret;
2059 }
2060
2061 /**
2062  *
2063  * @param array $item
2064  *
2065  * @return array
2066  * @throws InternalServerErrorException
2067  */
2068 function api_convert_item($item)
2069 {
2070         $body = api_add_attachments_to_body($item);
2071
2072         $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2073
2074         // Add pictures to the attachment array and remove them from the body
2075         $attachments = api_get_attachments($body, $item['uri-id']);
2076
2077         // Workaround for ostatus messages where the title is identically to the body
2078         $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
2079         $statusbody = trim(HTML::toPlaintext($html, 0));
2080
2081         // handle data: images
2082         $statusbody = api_format_items_embeded_images($item, $statusbody);
2083
2084         $statustitle = trim($item['title']);
2085
2086         if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2087                 $statustext = trim($statusbody);
2088         } else {
2089                 $statustext = trim($statustitle."\n\n".$statusbody);
2090         }
2091
2092         if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2093                 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2094         }
2095
2096         $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2097
2098         // Workaround for clients with limited HTML parser functionality
2099         $search = ["<br>", "<blockquote>", "</blockquote>",
2100                         "<h1>", "</h1>", "<h2>", "</h2>",
2101                         "<h3>", "</h3>", "<h4>", "</h4>",
2102                         "<h5>", "</h5>", "<h6>", "</h6>"];
2103         $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2104                         "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2105                         "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2106                         "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2107         $statushtml = str_replace($search, $replace, $statushtml);
2108
2109         if ($item['title'] != "") {
2110                 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2111         }
2112
2113         do {
2114                 $oldtext = $statushtml;
2115                 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2116         } while ($oldtext != $statushtml);
2117
2118         if (substr($statushtml, 0, 4) == '<br>') {
2119                 $statushtml = substr($statushtml, 4);
2120         }
2121
2122         if (substr($statushtml, 0, -4) == '<br>') {
2123                 $statushtml = substr($statushtml, -4);
2124         }
2125
2126         // feeds without body should contain the link
2127         if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2128                 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2129         }
2130
2131         return [
2132                 "text" => $statustext,
2133                 "html" => $statushtml,
2134                 "attachments" => $attachments,
2135                 "entities" => $entities
2136         ];
2137 }
2138
2139 /**
2140  * Add media attachments to the body
2141  *
2142  * @param array $item
2143  * @return string body with added media
2144  */
2145 function api_add_attachments_to_body(array $item)
2146 {
2147         $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2148
2149         if (strpos($body, '[/img]') !== false) {
2150                 return $body;
2151         }
2152
2153         foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2154                 if (!empty($media['preview'])) {
2155                         $description = $media['description'] ?: $media['name'];
2156                         if (!empty($description)) {
2157                                 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2158                         } else {
2159                                 $body .= "\n[img]" . $media['preview'] .'[/img]';
2160                         }
2161                 }
2162         }
2163
2164         return $body;
2165 }
2166
2167 /**
2168  *
2169  * @param string $body
2170  * @param int    $uriid
2171  *
2172  * @return array
2173  * @throws InternalServerErrorException
2174  */
2175 function api_get_attachments(&$body, $uriid)
2176 {
2177         $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2178         $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2179
2180         $URLSearchString = "^\[\]";
2181         if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2182                 return [];
2183         }
2184
2185         // Remove all embedded pictures, since they are added as attachments
2186         foreach ($images[0] as $orig) {
2187                 $body = str_replace($orig, '', $body);
2188         }
2189
2190         $attachments = [];
2191
2192         foreach ($images[1] as $image) {
2193                 $imagedata = Images::getInfoFromURLCached($image);
2194
2195                 if ($imagedata) {
2196                         $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2197                 }
2198         }
2199
2200         return $attachments;
2201 }
2202
2203 /**
2204  *
2205  * @param string $text
2206  * @param string $bbcode
2207  *
2208  * @return array
2209  * @throws InternalServerErrorException
2210  * @todo Links at the first character of the post
2211  */
2212 function api_get_entitities(&$text, $bbcode, $uriid)
2213 {
2214         $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2215
2216         if ($include_entities != "true") {
2217                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2218
2219                 foreach ($images[1] as $image) {
2220                         $replace = Post\Link::getByLink($uriid, $image);
2221                         $text = str_replace($image, $replace, $text);
2222                 }
2223                 return [];
2224         }
2225
2226         $bbcode = BBCode::cleanPictureLinks($bbcode);
2227
2228         // Change pure links in text to bbcode uris
2229         $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2230
2231         $entities = [];
2232         $entities["hashtags"] = [];
2233         $entities["symbols"] = [];
2234         $entities["urls"] = [];
2235         $entities["user_mentions"] = [];
2236
2237         $URLSearchString = "^\[\]";
2238
2239         $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2240
2241         $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2242         $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2243
2244         $bbcode = preg_replace(
2245                 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2246                 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2247                 $bbcode
2248         );
2249         $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2250
2251         $bbcode = preg_replace(
2252                 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2253                 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2254                 $bbcode
2255         );
2256         $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2257
2258         $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2259
2260         preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2261
2262         $ordered_urls = [];
2263         foreach ($urls[1] as $id => $url) {
2264                 $start = iconv_strpos($text, $url, 0, "UTF-8");
2265                 if (!($start === false)) {
2266                         $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2267                 }
2268         }
2269
2270         ksort($ordered_urls);
2271
2272         $offset = 0;
2273
2274         foreach ($ordered_urls as $url) {
2275                 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2276                         && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2277                 ) {
2278                         $display_url = $url["title"];
2279                 } else {
2280                         $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2281                         $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2282
2283                         if (strlen($display_url) > 26) {
2284                                 $display_url = substr($display_url, 0, 25)."…";
2285                         }
2286                 }
2287
2288                 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2289                 if (!($start === false)) {
2290                         $entities["urls"][] = ["url" => $url["url"],
2291                                                         "expanded_url" => $url["url"],
2292                                                         "display_url" => $display_url,
2293                                                         "indices" => [$start, $start+strlen($url["url"])]];
2294                         $offset = $start + 1;
2295                 }
2296         }
2297
2298         preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2299         $ordered_images = [];
2300         foreach ($images as $image) {
2301                 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2302                 if (!($start === false)) {
2303                         $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2304                 }
2305         }
2306
2307         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2308         foreach ($images[1] as $image) {
2309                 $start = iconv_strpos($text, $image, 0, "UTF-8");
2310                 if (!($start === false)) {
2311                         $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2312                 }
2313         }
2314
2315         $offset = 0;
2316
2317         foreach ($ordered_images as $image) {
2318                 $url = $image['url'];
2319                 $ext_alt_text = $image['alt'];
2320
2321                 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2322                 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2323
2324                 if (strlen($display_url) > 26) {
2325                         $display_url = substr($display_url, 0, 25)."…";
2326                 }
2327
2328                 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2329                 if (!($start === false)) {
2330                         $image = Images::getInfoFromURLCached($url);
2331                         if ($image) {
2332                                 $media_url = Post\Link::getByLink($uriid, $url);
2333                                 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2334
2335                                 $entities["media"][] = [
2336                                                         "id" => $start+1,
2337                                                         "id_str" => (string) ($start + 1),
2338                                                         "indices" => [$start, $start+strlen($url)],
2339                                                         "media_url" => Strings::normaliseLink($media_url),
2340                                                         "media_url_https" => $media_url,
2341                                                         "url" => $url,
2342                                                         "display_url" => $display_url,
2343                                                         "expanded_url" => $url,
2344                                                         "ext_alt_text" => $ext_alt_text,
2345                                                         "type" => "photo",
2346                                                         "sizes" => $sizes];
2347                         }
2348                         $offset = $start + 1;
2349                 }
2350         }
2351
2352         return $entities;
2353 }
2354
2355 /**
2356  *
2357  * @param array $item
2358  * @param string $text
2359  *
2360  * @return string
2361  */
2362 function api_format_items_embeded_images($item, $text)
2363 {
2364         $text = preg_replace_callback(
2365                 '|data:image/([^;]+)[^=]+=*|m',
2366                 function () use ($item) {
2367                         return DI::baseUrl() . '/display/' . $item['guid'];
2368                 },
2369                 $text
2370         );
2371         return $text;
2372 }
2373
2374 /**
2375  * return <a href='url'>name</a> as array
2376  *
2377  * @param string $txt text
2378  * @return array
2379  *                      'name' => 'name',
2380  *                      'url => 'url'
2381  */
2382 function api_contactlink_to_array($txt)
2383 {
2384         $match = [];
2385         $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2386         if ($r && count($match)==3) {
2387                 $res = [
2388                         'name' => $match[2],
2389                         'url' => $match[1]
2390                 ];
2391         } else {
2392                 $res = [
2393                         'name' => $txt,
2394                         'url' => ""
2395                 ];
2396         }
2397         return $res;
2398 }
2399
2400
2401 /**
2402  * return likes, dislikes and attend status for item
2403  *
2404  * @param array  $item array
2405  * @param string $type Return type (atom, rss, xml, json)
2406  *
2407  * @return array
2408  *            likes => int count,
2409  *            dislikes => int count
2410  * @throws BadRequestException
2411  * @throws ImagickException
2412  * @throws InternalServerErrorException
2413  * @throws UnauthorizedException
2414  */
2415 function api_format_items_activities($item, $type = "json")
2416 {
2417         $activities = [
2418                 'like' => [],
2419                 'dislike' => [],
2420                 'attendyes' => [],
2421                 'attendno' => [],
2422                 'attendmaybe' => [],
2423                 'announce' => [],
2424         ];
2425
2426         $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2427         $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2428
2429         while ($parent_item = Post::fetch($ret)) {
2430                 // not used as result should be structured like other user data
2431                 //builtin_activity_puller($i, $activities);
2432
2433                 // get user data and add it to the array of the activity
2434                 $user = DI::twitterUser()->createFromContactId($parent_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2435                 switch ($parent_item['verb']) {
2436                         case Activity::LIKE:
2437                                 $activities['like'][] = $user;
2438                                 break;
2439                         case Activity::DISLIKE:
2440                                 $activities['dislike'][] = $user;
2441                                 break;
2442                         case Activity::ATTEND:
2443                                 $activities['attendyes'][] = $user;
2444                                 break;
2445                         case Activity::ATTENDNO:
2446                                 $activities['attendno'][] = $user;
2447                                 break;
2448                         case Activity::ATTENDMAYBE:
2449                                 $activities['attendmaybe'][] = $user;
2450                                 break;
2451                         case Activity::ANNOUNCE:
2452                                 $activities['announce'][] = $user;
2453                                 break;
2454                         default:
2455                                 break;
2456                 }
2457         }
2458
2459         DBA::close($ret);
2460
2461         if ($type == "xml") {
2462                 $xml_activities = [];
2463                 foreach ($activities as $k => $v) {
2464                         // change xml element from "like" to "friendica:like"
2465                         $xml_activities["friendica:".$k] = $v;
2466                         // add user data into xml output
2467                         $k_user = 0;
2468                         foreach ($v as $user) {
2469                                 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2470                         }
2471                 }
2472                 $activities = $xml_activities;
2473         }
2474
2475         return $activities;
2476 }
2477
2478 /**
2479  * format items to be returned by api
2480  *
2481  * @param array  $items       array of items
2482  * @param array  $user_info
2483  * @param bool   $filter_user filter items by $user_info
2484  * @param string $type        Return type (atom, rss, xml, json)
2485  * @return array
2486  * @throws BadRequestException
2487  * @throws ImagickException
2488  * @throws InternalServerErrorException
2489  * @throws UnauthorizedException
2490  */
2491 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2492 {
2493         $a = DI::app();
2494
2495         $ret = [];
2496
2497         if (empty($items)) {
2498                 return $ret;
2499         }
2500
2501         foreach ((array)$items as $item) {
2502                 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2503
2504                 // Look if the posts are matching if they should be filtered by user id
2505                 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2506                         continue;
2507                 }
2508
2509                 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2510
2511                 $ret[] = $status;
2512         }
2513
2514         return $ret;
2515 }
2516
2517 /**
2518  * @param array  $item       Item record
2519  * @param string $type       Return format (atom, rss, xml, json)
2520  * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2521  * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2522  * @param array $owner_user  User record of the item owner, can be provided by api_item_get_user()
2523  * @return array API-formatted status
2524  * @throws BadRequestException
2525  * @throws ImagickException
2526  * @throws InternalServerErrorException
2527  * @throws UnauthorizedException
2528  */
2529 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2530 {
2531         $a = DI::app();
2532
2533         if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2534                 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2535         }
2536
2537         DI::contentItem()->localize($item);
2538
2539         $in_reply_to = api_in_reply_to($item);
2540
2541         $converted = api_convert_item($item);
2542
2543         if ($type == "xml") {
2544                 $geo = "georss:point";
2545         } else {
2546                 $geo = "geo";
2547         }
2548
2549         $status = [
2550                 'text'          => $converted["text"],
2551                 'truncated' => false,
2552                 'created_at'=> api_date($item['created']),
2553                 'in_reply_to_status_id' => $in_reply_to['status_id'],
2554                 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2555                 'source'    => (($item['app']) ? $item['app'] : 'web'),
2556                 'id'            => intval($item['id']),
2557                 'id_str'        => (string) intval($item['id']),
2558                 'in_reply_to_user_id' => $in_reply_to['user_id'],
2559                 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2560                 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2561                 $geo => null,
2562                 'favorited' => $item['starred'] ? true : false,
2563                 'user' =>  $status_user,
2564                 'friendica_author' => $author_user,
2565                 'friendica_owner' => $owner_user,
2566                 'friendica_private' => $item['private'] == Item::PRIVATE,
2567                 //'entities' => NULL,
2568                 'statusnet_html' => $converted["html"],
2569                 'statusnet_conversation_id' => $item['parent'],
2570                 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2571                 'friendica_activities' => api_format_items_activities($item, $type),
2572                 'friendica_title' => $item['title'],
2573                 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
2574         ];
2575
2576         if (count($converted["attachments"]) > 0) {
2577                 $status["attachments"] = $converted["attachments"];
2578         }
2579
2580         if (count($converted["entities"]) > 0) {
2581                 $status["entities"] = $converted["entities"];
2582         }
2583
2584         if ($status["source"] == 'web') {
2585                 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2586         } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2587                 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2588         }
2589
2590         $retweeted_item = [];
2591         $quoted_item = [];
2592
2593         if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2594                 $announce = api_get_announce($item);
2595                 if (!empty($announce)) {
2596                         $retweeted_item = $item;
2597                         $item = $announce;
2598                         $status['friendica_owner'] = DI::twitterUser()->createFromContactId($announce['author-id'], BaseApi::getCurrentUserID())->toArray();
2599                 }
2600         }
2601
2602         if (!empty($quoted_item)) {
2603                 if ($quoted_item['id'] != $item['id']) {
2604                         $quoted_status = api_format_item($quoted_item);
2605                         /// @todo Only remove the attachments that are also contained in the quotes status
2606                         unset($status['attachments']);
2607                         unset($status['entities']);
2608                 } else {
2609                         $conv_quoted = api_convert_item($quoted_item);
2610                         $quoted_status = $status;
2611                         unset($quoted_status['attachments']);
2612                         unset($quoted_status['entities']);
2613                         unset($quoted_status['statusnet_conversation_id']);
2614                         $quoted_status['text'] = $conv_quoted['text'];
2615                         $quoted_status['statusnet_html'] = $conv_quoted['html'];
2616                         try {
2617                                 $quoted_status["user"] = DI::twitterUser()->createFromContactId($quoted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2618                         } catch (BadRequestException $e) {
2619                                 // user not found. should be found?
2620                                 /// @todo check if the user should be always found
2621                                 $quoted_status["user"] = [];
2622                         }
2623                 }
2624                 unset($quoted_status['friendica_author']);
2625                 unset($quoted_status['friendica_owner']);
2626                 unset($quoted_status['friendica_activities']);
2627                 unset($quoted_status['friendica_private']);
2628         }
2629
2630         if (!empty($retweeted_item)) {
2631                 $retweeted_status = $status;
2632                 unset($retweeted_status['friendica_author']);
2633                 unset($retweeted_status['friendica_owner']);
2634                 unset($retweeted_status['friendica_activities']);
2635                 unset($retweeted_status['friendica_private']);
2636                 unset($retweeted_status['statusnet_conversation_id']);
2637                 $status['user'] = $status['friendica_owner'];
2638                 try {
2639                         $retweeted_status["user"] = DI::twitterUser()->createFromContactId($retweeted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2640                 } catch (BadRequestException $e) {
2641                         // user not found. should be found?
2642                         /// @todo check if the user should be always found
2643                         $retweeted_status["user"] = [];
2644                 }
2645
2646                 $rt_converted = api_convert_item($retweeted_item);
2647
2648                 $retweeted_status['text'] = $rt_converted["text"];
2649                 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2650                 $retweeted_status['friendica_html'] = $rt_converted["html"];
2651                 $retweeted_status['created_at'] =  api_date($retweeted_item['created']);
2652
2653                 if (!empty($quoted_status)) {
2654                         $retweeted_status['quoted_status'] = $quoted_status;
2655                 }
2656
2657                 $status['friendica_author'] = $retweeted_status['user'];
2658                 $status['retweeted_status'] = $retweeted_status;
2659         } elseif (!empty($quoted_status)) {
2660                 $root_status = api_convert_item($item);
2661
2662                 $status['text'] = $root_status["text"];
2663                 $status['statusnet_html'] = $root_status["html"];
2664                 $status['quoted_status'] = $quoted_status;
2665         }
2666
2667         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2668         unset($status["user"]["uid"]);
2669         unset($status["user"]["self"]);
2670
2671         if ($item["coord"] != "") {
2672                 $coords = explode(' ', $item["coord"]);
2673                 if (count($coords) == 2) {
2674                         if ($type == "json") {
2675                                 $status["geo"] = ['type' => 'Point',
2676                                         'coordinates' => [(float) $coords[0],
2677                                                 (float) $coords[1]]];
2678                         } else {// Not sure if this is the official format - if someone founds a documentation we can check
2679                                 $status["georss:point"] = $item["coord"];
2680                         }
2681                 }
2682         }
2683
2684         return $status;
2685 }
2686
2687 /**
2688  * Returns all lists the user subscribes to.
2689  *
2690  * @param string $type Return type (atom, rss, xml, json)
2691  *
2692  * @return array|string
2693  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2694  */
2695 function api_lists_list($type)
2696 {
2697         $ret = [];
2698         /// @TODO $ret is not filled here?
2699         return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2700 }
2701
2702 /// @TODO move to top of file or somewhere better
2703 api_register_func('api/lists/list', 'api_lists_list', true);
2704 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2705
2706 /**
2707  * Returns all groups the user owns.
2708  *
2709  * @param string $type Return type (atom, rss, xml, json)
2710  *
2711  * @return array|string
2712  * @throws BadRequestException
2713  * @throws ForbiddenException
2714  * @throws ImagickException
2715  * @throws InternalServerErrorException
2716  * @throws UnauthorizedException
2717  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2718  */
2719 function api_lists_ownerships($type)
2720 {
2721         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2722
2723         // params
2724         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2725         $uid = $user_info['uid'];
2726
2727         $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2728
2729         // loop through all groups
2730         $lists = [];
2731         foreach ($groups as $group) {
2732                 if ($group['visible']) {
2733                         $mode = 'public';
2734                 } else {
2735                         $mode = 'private';
2736                 }
2737                 $lists[] = [
2738                         'name' => $group['name'],
2739                         'id' => intval($group['id']),
2740                         'id_str' => (string) $group['id'],
2741                         'user' => $user_info,
2742                         'mode' => $mode
2743                 ];
2744         }
2745         return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2746 }
2747
2748 /// @TODO move to top of file or somewhere better
2749 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2750
2751 /**
2752  * Returns recent statuses from users in the specified group.
2753  *
2754  * @param string $type Return type (atom, rss, xml, json)
2755  *
2756  * @return array|string
2757  * @throws BadRequestException
2758  * @throws ForbiddenException
2759  * @throws ImagickException
2760  * @throws InternalServerErrorException
2761  * @throws UnauthorizedException
2762  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2763  */
2764 function api_lists_statuses($type)
2765 {
2766         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2767
2768         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2769
2770         unset($_REQUEST["user_id"]);
2771         unset($_GET["user_id"]);
2772
2773         unset($_REQUEST["screen_name"]);
2774         unset($_GET["screen_name"]);
2775
2776         if (empty($_REQUEST['list_id'])) {
2777                 throw new BadRequestException('list_id not specified');
2778         }
2779
2780         // params
2781         $count = $_REQUEST['count'] ?? 20;
2782         $page = $_REQUEST['page'] ?? 1;
2783         $since_id = $_REQUEST['since_id'] ?? 0;
2784         $max_id = $_REQUEST['max_id'] ?? 0;
2785         $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2786         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2787
2788         $start = max(0, ($page - 1) * $count);
2789
2790         $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2791         $gids = array_column($groups, 'contact-id');
2792         $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2793         $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2794
2795         if ($max_id > 0) {
2796                 $condition[0] .= " AND `id` <= ?";
2797                 $condition[] = $max_id;
2798         }
2799         if ($exclude_replies > 0) {
2800                 $condition[0] .= ' AND `gravity` = ?';
2801                 $condition[] = GRAVITY_PARENT;
2802         }
2803         if ($conversation_id > 0) {
2804                 $condition[0] .= " AND `parent` = ?";
2805                 $condition[] = $conversation_id;
2806         }
2807
2808         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2809         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2810
2811         $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2812
2813         $data = ['status' => $items];
2814         switch ($type) {
2815                 case "atom":
2816                         break;
2817                 case "rss":
2818                         $data = api_rss_extra($data, $user_info);
2819                         break;
2820         }
2821
2822         return DI::apiResponse()->formatData("statuses", $type, $data);
2823 }
2824
2825 /// @TODO move to top of file or somewhere better
2826 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2827
2828 /**
2829  * Returns either the friends of the follower list
2830  *
2831  * Considers friends and followers lists to be private and won't return
2832  * anything if any user_id parameter is passed.
2833  *
2834  * @param string $qtype Either "friends" or "followers"
2835  * @return boolean|array
2836  * @throws BadRequestException
2837  * @throws ForbiddenException
2838  * @throws ImagickException
2839  * @throws InternalServerErrorException
2840  * @throws UnauthorizedException
2841  */
2842 function api_statuses_f($qtype)
2843 {
2844         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2845
2846         // pagination
2847         $count = $_GET['count'] ?? 20;
2848         $page = $_GET['page'] ?? 1;
2849
2850         $start = max(0, ($page - 1) * $count);
2851
2852         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2853
2854         if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2855                 /* this is to stop Hotot to load friends multiple times
2856                 *  I'm not sure if I'm missing return something or
2857                 *  is a bug in hotot. Workaround, meantime
2858                 */
2859
2860                 /*$ret=Array();
2861                 return array('$users' => $ret);*/
2862                 return false;
2863         }
2864
2865         $sql_extra = '';
2866         if ($qtype == 'friends') {
2867                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2868         } elseif ($qtype == 'followers') {
2869                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2870         }
2871
2872         // friends and followers only for self
2873         if ($user_info['self'] == 0) {
2874                 $sql_extra = " AND false ";
2875         }
2876
2877         if ($qtype == 'blocks') {
2878                 $sql_filter = 'AND `blocked` AND NOT `pending`';
2879         } elseif ($qtype == 'incoming') {
2880                 $sql_filter = 'AND `pending`';
2881         } else {
2882                 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2883         }
2884
2885         // @todo This query most likely can be replaced with a Contact::select...
2886         $r = DBA::toArray(DBA::p(
2887                 "SELECT `id`
2888                 FROM `contact`
2889                 WHERE `uid` = ?
2890                 AND NOT `self`
2891                 $sql_filter
2892                 $sql_extra
2893                 ORDER BY `nick`
2894                 LIMIT ?, ?",
2895                 api_user(),
2896                 $start,
2897                 $count
2898         ));
2899
2900         $ret = [];
2901         foreach ($r as $cid) {
2902                 $user = DI::twitterUser()->createFromContactId($cid['id'], BaseApi::getCurrentUserID())->toArray();
2903                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2904                 unset($user["uid"]);
2905                 unset($user["self"]);
2906
2907                 if ($user) {
2908                         $ret[] = $user;
2909                 }
2910         }
2911
2912         return ['user' => $ret];
2913 }
2914
2915
2916 /**
2917  * Returns the list of friends of the provided user
2918  *
2919  * @deprecated By Twitter API in favor of friends/list
2920  *
2921  * @param string $type Either "json" or "xml"
2922  * @return boolean|string|array
2923  * @throws BadRequestException
2924  * @throws ForbiddenException
2925  */
2926 function api_statuses_friends($type)
2927 {
2928         $data =  api_statuses_f("friends");
2929         if ($data === false) {
2930                 return false;
2931         }
2932         return DI::apiResponse()->formatData("users", $type, $data);
2933 }
2934
2935 /**
2936  * Returns the list of followers of the provided user
2937  *
2938  * @deprecated By Twitter API in favor of friends/list
2939  *
2940  * @param string $type Either "json" or "xml"
2941  * @return boolean|string|array
2942  * @throws BadRequestException
2943  * @throws ForbiddenException
2944  */
2945 function api_statuses_followers($type)
2946 {
2947         $data = api_statuses_f("followers");
2948         if ($data === false) {
2949                 return false;
2950         }
2951         return DI::apiResponse()->formatData("users", $type, $data);
2952 }
2953
2954 /// @TODO move to top of file or somewhere better
2955 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2956 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2957
2958 /**
2959  * Returns the list of blocked users
2960  *
2961  * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
2962  *
2963  * @param string $type Either "json" or "xml"
2964  *
2965  * @return boolean|string|array
2966  * @throws BadRequestException
2967  * @throws ForbiddenException
2968  */
2969 function api_blocks_list($type)
2970 {
2971         $data =  api_statuses_f('blocks');
2972         if ($data === false) {
2973                 return false;
2974         }
2975         return DI::apiResponse()->formatData("users", $type, $data);
2976 }
2977
2978 /// @TODO move to top of file or somewhere better
2979 api_register_func('api/blocks/list', 'api_blocks_list', true);
2980
2981 /**
2982  * Returns the list of pending users IDs
2983  *
2984  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
2985  *
2986  * @param string $type Either "json" or "xml"
2987  *
2988  * @return boolean|string|array
2989  * @throws BadRequestException
2990  * @throws ForbiddenException
2991  */
2992 function api_friendships_incoming($type)
2993 {
2994         $data =  api_statuses_f('incoming');
2995         if ($data === false) {
2996                 return false;
2997         }
2998
2999         $ids = [];
3000         foreach ($data['user'] as $user) {
3001                 $ids[] = $user['id'];
3002         }
3003
3004         return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
3005 }
3006
3007 /// @TODO move to top of file or somewhere better
3008 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3009
3010 /**
3011  * Sends a new direct message.
3012  *
3013  * @param string $type Return type (atom, rss, xml, json)
3014  *
3015  * @return array|string
3016  * @throws BadRequestException
3017  * @throws ForbiddenException
3018  * @throws ImagickException
3019  * @throws InternalServerErrorException
3020  * @throws NotFoundException
3021  * @throws UnauthorizedException
3022  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3023  */
3024 function api_direct_messages_new($type)
3025 {
3026         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3027
3028         $uid = BaseApi::getCurrentUserID();
3029         if (empty($uid)) {
3030                 throw new ForbiddenException();
3031         }
3032         
3033         if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3034                 return;
3035         }
3036
3037         $sender = DI::twitterUser()->createFromUserId($uid)->toArray();
3038
3039         $recipient = null;
3040         if (!empty($_POST['screen_name'])) {
3041                 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => api_user(), 'nick' => $_POST['screen_name']]);
3042                 if (DBA::isResult($contacts)) {
3043                         // Selecting the id by priority, friendica first
3044                         api_best_nickname($contacts);
3045
3046                         $recipient = DI::twitterUser()->createFromContactId($contacts[0]['id'], $uid)->toArray();
3047                 }
3048         } else {
3049                 $recipient = api_get_user($_POST['user_id']);
3050         }
3051
3052         if (empty($recipient)) {
3053                 throw new NotFoundException('Recipient not found');
3054         }
3055
3056         $replyto = '';
3057         if (!empty($_REQUEST['replyto'])) {
3058                 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => api_user(), 'id' => $_REQUEST['replyto']]);
3059                 $replyto = $mail['parent-uri'];
3060                 $sub     = $mail['title'];
3061         } else {
3062                 if (!empty($_REQUEST['title'])) {
3063                         $sub = $_REQUEST['title'];
3064                 } else {
3065                         $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3066                 }
3067         }
3068
3069         $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3070
3071         if ($id > -1) {
3072                 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
3073                 $ret = api_format_messages($mail, $recipient, $sender);
3074         } else {
3075                 $ret = ["error" => $id];
3076         }
3077
3078         $data = ['direct_message'=>$ret];
3079
3080         switch ($type) {
3081                 case "atom":
3082                         break;
3083                 case "rss":
3084                         $data = api_rss_extra($data, $sender);
3085                         break;
3086         }
3087
3088         return DI::apiResponse()->formatData("direct-messages", $type, $data);
3089 }
3090
3091 /// @TODO move to top of file or somewhere better
3092 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3093
3094 /**
3095  * delete a direct_message from mail table through api
3096  *
3097  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3098  * @return string|array
3099  * @throws BadRequestException
3100  * @throws ForbiddenException
3101  * @throws ImagickException
3102  * @throws InternalServerErrorException
3103  * @throws UnauthorizedException
3104  * @see   https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3105  */
3106 function api_direct_messages_destroy($type)
3107 {
3108         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3109
3110         // params
3111         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3112         //required
3113         $id = $_REQUEST['id'] ?? 0;
3114         // optional
3115         $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3116         $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3117         /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3118
3119         $uid = $user_info['uid'];
3120         // error if no id or parenturi specified (for clients posting parent-uri as well)
3121         if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3122                 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3123                 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3124         }
3125
3126         // BadRequestException if no id specified (for clients using Twitter API)
3127         if ($id == 0) {
3128                 throw new BadRequestException('Message id not specified');
3129         }
3130
3131         // add parent-uri to sql command if specified by calling app
3132         $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3133
3134         // error message if specified id is not in database
3135         if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
3136                 if ($verbose == "true") {
3137                         $answer = ['result' => 'error', 'message' => 'message id not in database'];
3138                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3139                 }
3140                 /// @todo BadRequestException ok for Twitter API clients?
3141                 throw new BadRequestException('message id not in database');
3142         }
3143
3144         // delete message
3145         $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
3146
3147         if ($verbose == "true") {
3148                 if ($result) {
3149                         // return success
3150                         $answer = ['result' => 'ok', 'message' => 'message deleted'];
3151                         return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
3152                 } else {
3153                         $answer = ['result' => 'error', 'message' => 'unknown error'];
3154                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3155                 }
3156         }
3157         /// @todo return JSON data like Twitter API not yet implemented
3158 }
3159
3160 /// @TODO move to top of file or somewhere better
3161 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3162
3163 /**
3164  * Unfollow Contact
3165  *
3166  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3167  * @return string|array
3168  * @throws HTTPException\BadRequestException
3169  * @throws HTTPException\ExpectationFailedException
3170  * @throws HTTPException\ForbiddenException
3171  * @throws HTTPException\InternalServerErrorException
3172  * @throws HTTPException\NotFoundException
3173  * @see   https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3174  */
3175 function api_friendships_destroy($type)
3176 {
3177         $uid = api_user();
3178
3179         if ($uid === false) {
3180                 throw new HTTPException\ForbiddenException();
3181         }
3182
3183         $owner = User::getOwnerDataById($uid);
3184         if (!$owner) {
3185                 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3186                 throw new HTTPException\NotFoundException('Error Processing Request');
3187         }
3188
3189         $contact_id = $_REQUEST['user_id'] ?? 0;
3190
3191         if (empty($contact_id)) {
3192                 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3193                 throw new HTTPException\BadRequestException('no user_id specified');
3194         }
3195
3196         // Get Contact by given id
3197         $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3198
3199         if(!DBA::isResult($contact)) {
3200                 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3201                 throw new HTTPException\NotFoundException('no contact found to given ID');
3202         }
3203
3204         $url = $contact['url'];
3205
3206         $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3207                         $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3208                         Strings::normaliseLink($url), $url];
3209         $contact = DBA::selectFirst('contact', [], $condition);
3210
3211         if (!DBA::isResult($contact)) {
3212                 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3213                 throw new HTTPException\NotFoundException('Not following Contact');
3214         }
3215
3216         try {
3217                 $result = Contact::terminateFriendship($owner, $contact);
3218
3219                 if ($result === null) {
3220                         Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3221                         throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3222                 }
3223
3224                 if ($result === false) {
3225                         throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3226                 }
3227         } catch (Exception $e) {
3228                 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3229                 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3230         }
3231
3232         // "uid" and "self" are only needed for some internal stuff, so remove it from here
3233         unset($contact['uid']);
3234         unset($contact['self']);
3235
3236         // Set screen_name since Twidere requests it
3237         $contact['screen_name'] = $contact['nick'];
3238
3239         return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
3240 }
3241
3242 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3243
3244 /**
3245  *
3246  * @param string $type Return type (atom, rss, xml, json)
3247  * @param string $box
3248  * @param string $verbose
3249  *
3250  * @return array|string
3251  * @throws BadRequestException
3252  * @throws ForbiddenException
3253  * @throws ImagickException
3254  * @throws InternalServerErrorException
3255  * @throws UnauthorizedException
3256  */
3257 function api_direct_messages_box($type, $box, $verbose)
3258 {
3259         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3260
3261         // params
3262         $count = $_GET['count'] ?? 20;
3263         $page = $_REQUEST['page'] ?? 1;
3264
3265         $since_id = $_REQUEST['since_id'] ?? 0;
3266         $max_id = $_REQUEST['max_id'] ?? 0;
3267
3268         $user_id = $_REQUEST['user_id'] ?? '';
3269         $screen_name = $_REQUEST['screen_name'] ?? '';
3270
3271         //  caller user info
3272         unset($_REQUEST["user_id"]);
3273         unset($_GET["user_id"]);
3274
3275         unset($_REQUEST["screen_name"]);
3276         unset($_GET["screen_name"]);
3277
3278         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3279
3280         $profile_url = $user_info["url"];
3281
3282         // pagination
3283         $start = max(0, ($page - 1) * $count);
3284
3285         $sql_extra = "";
3286
3287         // filters
3288         if ($box=="sentbox") {
3289                 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3290         } elseif ($box == "conversation") {
3291                 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '')  . "'";
3292         } elseif ($box == "all") {
3293                 $sql_extra = "true";
3294         } elseif ($box == "inbox") {
3295                 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3296         }
3297
3298         if ($max_id > 0) {
3299                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3300         }
3301
3302         if ($user_id != "") {
3303                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3304         } elseif ($screen_name !="") {
3305                 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3306         }
3307
3308         $r = DBA::toArray(DBA::p(
3309                 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND $sql_extra AND `mail`.`id` > ? ORDER BY `mail`.`id` DESC LIMIT ?,?",
3310                 api_user(),
3311                 $since_id,
3312                 $start,
3313                 $count
3314         ));
3315         if ($verbose == "true" && !DBA::isResult($r)) {
3316                 $answer = ['result' => 'error', 'message' => 'no mails available'];
3317                 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
3318         }
3319
3320         $ret = [];
3321         foreach ($r as $item) {
3322                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3323                         $recipient = $user_info;
3324                         $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
3325                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3326                         $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
3327                         $sender = $user_info;
3328                 }
3329
3330                 if (isset($recipient) && isset($sender)) {
3331                         $ret[] = api_format_messages($item, $recipient, $sender);
3332                 }
3333         }
3334
3335
3336         $data = ['direct_message' => $ret];
3337         switch ($type) {
3338                 case "atom":
3339                         break;
3340                 case "rss":
3341                         $data = api_rss_extra($data, $user_info);
3342                         break;
3343         }
3344
3345         return DI::apiResponse()->formatData("direct-messages", $type, $data);
3346 }
3347
3348 /**
3349  * Returns the most recent direct messages sent by the user.
3350  *
3351  * @param string $type Return type (atom, rss, xml, json)
3352  *
3353  * @return array|string
3354  * @throws BadRequestException
3355  * @throws ForbiddenException
3356  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3357  */
3358 function api_direct_messages_sentbox($type)
3359 {
3360         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3361         return api_direct_messages_box($type, "sentbox", $verbose);
3362 }
3363
3364 /**
3365  * Returns the most recent direct messages sent to the user.
3366  *
3367  * @param string $type Return type (atom, rss, xml, json)
3368  *
3369  * @return array|string
3370  * @throws BadRequestException
3371  * @throws ForbiddenException
3372  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3373  */
3374 function api_direct_messages_inbox($type)
3375 {
3376         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3377         return api_direct_messages_box($type, "inbox", $verbose);
3378 }
3379
3380 /**
3381  *
3382  * @param string $type Return type (atom, rss, xml, json)
3383  *
3384  * @return array|string
3385  * @throws BadRequestException
3386  * @throws ForbiddenException
3387  */
3388 function api_direct_messages_all($type)
3389 {
3390         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3391         return api_direct_messages_box($type, "all", $verbose);
3392 }
3393
3394 /**
3395  *
3396  * @param string $type Return type (atom, rss, xml, json)
3397  *
3398  * @return array|string
3399  * @throws BadRequestException
3400  * @throws ForbiddenException
3401  */
3402 function api_direct_messages_conversation($type)
3403 {
3404         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3405         return api_direct_messages_box($type, "conversation", $verbose);
3406 }
3407
3408 /// @TODO move to top of file or somewhere better
3409 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3410 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3411 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3412 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3413
3414 /**
3415  * list all photos of the authenticated user
3416  *
3417  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3418  * @return string|array
3419  * @throws ForbiddenException
3420  * @throws InternalServerErrorException
3421  */
3422 function api_fr_photos_list($type)
3423 {
3424         if (api_user() === false) {
3425                 throw new ForbiddenException();
3426         }
3427         $r = DBA::toArray(DBA::p(
3428                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3429                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3430                 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
3431                 local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
3432         ));
3433         $typetoext = [
3434                 'image/jpeg' => 'jpg',
3435                 'image/png' => 'png',
3436                 'image/gif' => 'gif'
3437         ];
3438         $data = ['photo'=>[]];
3439         if (DBA::isResult($r)) {
3440                 foreach ($r as $rr) {
3441                         $photo = [];
3442                         $photo['id'] = $rr['resource-id'];
3443                         $photo['album'] = $rr['album'];
3444                         $photo['filename'] = $rr['filename'];
3445                         $photo['type'] = $rr['type'];
3446                         $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3447                         $photo['created'] = $rr['created'];
3448                         $photo['edited'] = $rr['edited'];
3449                         $photo['desc'] = $rr['desc'];
3450
3451                         if ($type == "xml") {
3452                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3453                         } else {
3454                                 $photo['thumb'] = $thumb;
3455                                 $data['photo'][] = $photo;
3456                         }
3457                 }
3458         }
3459         return DI::apiResponse()->formatData("photos", $type, $data);
3460 }
3461
3462 /**
3463  * upload a new photo or change an existing photo
3464  *
3465  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3466  * @return string|array
3467  * @throws BadRequestException
3468  * @throws ForbiddenException
3469  * @throws ImagickException
3470  * @throws InternalServerErrorException
3471  * @throws NotFoundException
3472  */
3473 function api_fr_photo_create_update($type)
3474 {
3475         if (api_user() === false) {
3476                 throw new ForbiddenException();
3477         }
3478         // input params
3479         $photo_id  = $_REQUEST['photo_id']  ?? null;
3480         $desc      = $_REQUEST['desc']      ?? null;
3481         $album     = $_REQUEST['album']     ?? null;
3482         $album_new = $_REQUEST['album_new'] ?? null;
3483         $allow_cid = $_REQUEST['allow_cid'] ?? null;
3484         $deny_cid  = $_REQUEST['deny_cid' ] ?? null;
3485         $allow_gid = $_REQUEST['allow_gid'] ?? null;
3486         $deny_gid  = $_REQUEST['deny_gid' ] ?? null;
3487         $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3488
3489         // do several checks on input parameters
3490         // we do not allow calls without album string
3491         if ($album == null) {
3492                 throw new BadRequestException("no albumname specified");
3493         }
3494         // if photo_id == null --> we are uploading a new photo
3495         if ($photo_id == null) {
3496                 $mode = "create";
3497
3498                 // error if no media posted in create-mode
3499                 if (empty($_FILES['media'])) {
3500                         // Output error
3501                         throw new BadRequestException("no media data submitted");
3502                 }
3503
3504                 // album_new will be ignored in create-mode
3505                 $album_new = "";
3506         } else {
3507                 $mode = "update";
3508
3509                 // check if photo is existing in databasei
3510                 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
3511                         throw new BadRequestException("photo not available");
3512                 }
3513         }
3514
3515         // checks on acl strings provided by clients
3516         $acl_input_error = false;
3517         $acl_input_error |= check_acl_input($allow_cid);
3518         $acl_input_error |= check_acl_input($deny_cid);
3519         $acl_input_error |= check_acl_input($allow_gid);
3520         $acl_input_error |= check_acl_input($deny_gid);
3521         if ($acl_input_error) {
3522                 throw new BadRequestException("acl data invalid");
3523         }
3524         // now let's upload the new media in create-mode
3525         if ($mode == "create") {
3526                 $media = $_FILES['media'];
3527                 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, Photo::DEFAULT, $visibility);
3528
3529                 // return success of updating or error message
3530                 if (!is_null($data)) {
3531                         return DI::apiResponse()->formatData("photo_create", $type, $data);
3532                 } else {
3533                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3534                 }
3535         }
3536
3537         // now let's do the changes in update-mode
3538         if ($mode == "update") {
3539                 $updated_fields = [];
3540
3541                 if (!is_null($desc)) {
3542                         $updated_fields['desc'] = $desc;
3543                 }
3544
3545                 if (!is_null($album_new)) {
3546                         $updated_fields['album'] = $album_new;
3547                 }
3548
3549                 if (!is_null($allow_cid)) {
3550                         $allow_cid = trim($allow_cid);
3551                         $updated_fields['allow_cid'] = $allow_cid;
3552                 }
3553
3554                 if (!is_null($deny_cid)) {
3555                         $deny_cid = trim($deny_cid);
3556                         $updated_fields['deny_cid'] = $deny_cid;
3557                 }
3558
3559                 if (!is_null($allow_gid)) {
3560                         $allow_gid = trim($allow_gid);
3561                         $updated_fields['allow_gid'] = $allow_gid;
3562                 }
3563
3564                 if (!is_null($deny_gid)) {
3565                         $deny_gid = trim($deny_gid);
3566                         $updated_fields['deny_gid'] = $deny_gid;
3567                 }
3568
3569                 $result = false;
3570                 if (count($updated_fields) > 0) {
3571                         $nothingtodo = false;
3572                         $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
3573                 } else {
3574                         $nothingtodo = true;
3575                 }
3576
3577                 if (!empty($_FILES['media'])) {
3578                         $nothingtodo = false;
3579                         $media = $_FILES['media'];
3580                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
3581                         if (!is_null($data)) {
3582                                 return DI::apiResponse()->formatData("photo_update", $type, $data);
3583                         }
3584                 }
3585
3586                 // return success of updating or error message
3587                 if ($result) {
3588                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3589                         return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3590                 } else {
3591                         if ($nothingtodo) {
3592                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3593                                 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3594                         }
3595                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3596                 }
3597         }
3598         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3599 }
3600
3601 /**
3602  * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3603  *
3604  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3605  * @return string|array
3606  * @throws BadRequestException
3607  * @throws ForbiddenException
3608  * @throws InternalServerErrorException
3609  * @throws NotFoundException
3610  */
3611 function api_fr_photo_detail($type)
3612 {
3613         if (api_user() === false) {
3614                 throw new ForbiddenException();
3615         }
3616         if (empty($_REQUEST['photo_id'])) {
3617                 throw new BadRequestException("No photo id.");
3618         }
3619
3620         $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3621         $photo_id = $_REQUEST['photo_id'];
3622
3623         // prepare json/xml output with data from database for the requested photo
3624         $data = prepare_photo_data($type, $scale, $photo_id);
3625
3626         return DI::apiResponse()->formatData("photo_detail", $type, $data);
3627 }
3628
3629
3630 /**
3631  * updates the profile image for the user (either a specified profile or the default profile)
3632  *
3633  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3634  *
3635  * @return string|array
3636  * @throws BadRequestException
3637  * @throws ForbiddenException
3638  * @throws ImagickException
3639  * @throws InternalServerErrorException
3640  * @throws NotFoundException
3641  * @see   https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3642  */
3643 function api_account_update_profile_image($type)
3644 {
3645         if (api_user() === false) {
3646                 throw new ForbiddenException();
3647         }
3648         // input params
3649         $profile_id = $_REQUEST['profile_id'] ?? 0;
3650
3651         // error if image data is missing
3652         if (empty($_FILES['image'])) {
3653                 throw new BadRequestException("no media data submitted");
3654         }
3655
3656         // check if specified profile id is valid
3657         if ($profile_id != 0) {
3658                 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
3659                 // error message if specified profile id is not in database
3660                 if (!DBA::isResult($profile)) {
3661                         throw new BadRequestException("profile_id not available");
3662                 }
3663                 $is_default_profile = $profile['is-default'];
3664         } else {
3665                 $is_default_profile = 1;
3666         }
3667
3668         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3669         $media = null;
3670         if (!empty($_FILES['image'])) {
3671                 $media = $_FILES['image'];
3672         } elseif (!empty($_FILES['media'])) {
3673                 $media = $_FILES['media'];
3674         }
3675         // save new profile image
3676         $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
3677
3678         // get filetype
3679         if (is_array($media['type'])) {
3680                 $filetype = $media['type'][0];
3681         } else {
3682                 $filetype = $media['type'];
3683         }
3684         if ($filetype == "image/jpeg") {
3685                 $fileext = "jpg";
3686         } elseif ($filetype == "image/png") {
3687                 $fileext = "png";
3688         } else {
3689                 throw new InternalServerErrorException('Unsupported filetype');
3690         }
3691
3692         // change specified profile or all profiles to the new resource-id
3693         if ($is_default_profile) {
3694                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
3695                 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3696         } else {
3697                 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3698                         'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3699                 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
3700         }
3701
3702         Contact::updateSelfFromUserID(api_user(), true);
3703
3704         // Update global directory in background
3705         Profile::publishUpdate(api_user());
3706
3707         // output for client
3708         if ($data) {
3709                 return api_account_verify_credentials($type);
3710         } else {
3711                 // SaveMediaToDatabase failed for some reason
3712                 throw new InternalServerErrorException("image upload failed");
3713         }
3714 }
3715
3716 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3717 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3718 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3719 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3720 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3721 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3722
3723 /**
3724  * Update user profile
3725  *
3726  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3727  *
3728  * @return array|string
3729  * @throws BadRequestException
3730  * @throws ForbiddenException
3731  * @throws ImagickException
3732  * @throws InternalServerErrorException
3733  * @throws UnauthorizedException
3734  */
3735 function api_account_update_profile($type)
3736 {
3737         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3738
3739         $local_user = api_user();
3740
3741         $api_user = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3742
3743         if (!empty($_POST['name'])) {
3744                 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
3745                 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
3746                 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
3747                 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3748         }
3749
3750         if (isset($_POST['description'])) {
3751                 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
3752                 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
3753                 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3754         }
3755
3756         Profile::publishUpdate($local_user);
3757
3758         return api_account_verify_credentials($type);
3759 }
3760
3761 /// @TODO move to top of file or somewhere better
3762 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3763
3764 /**
3765  *
3766  * @param string $acl_string
3767  * @return bool
3768  * @throws Exception
3769  */
3770 function check_acl_input($acl_string)
3771 {
3772         if (empty($acl_string)) {
3773                 return false;
3774         }
3775
3776         $contact_not_found = false;
3777
3778         // split <x><y><z> into array of cid's
3779         preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3780
3781         // check for each cid if it is available on server
3782         $cid_array = $array[0];
3783         foreach ($cid_array as $cid) {
3784                 $cid = str_replace("<", "", $cid);
3785                 $cid = str_replace(">", "", $cid);
3786                 $condition = ['id' => $cid, 'uid' => api_user()];
3787                 $contact_not_found |= !DBA::exists('contact', $condition);
3788         }
3789         return $contact_not_found;
3790 }
3791
3792 /**
3793  * @param string  $mediatype
3794  * @param array   $media
3795  * @param string  $type
3796  * @param string  $album
3797  * @param string  $allow_cid
3798  * @param string  $deny_cid
3799  * @param string  $allow_gid
3800  * @param string  $deny_gid
3801  * @param string  $desc
3802  * @param integer $phototype
3803  * @param boolean $visibility
3804  * @param string  $photo_id
3805  * @return array
3806  * @throws BadRequestException
3807  * @throws ForbiddenException
3808  * @throws ImagickException
3809  * @throws InternalServerErrorException
3810  * @throws NotFoundException
3811  * @throws UnauthorizedException
3812  */
3813 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype = 0, $visibility = false, $photo_id = null)
3814 {
3815         $visitor   = 0;
3816         $src = "";
3817         $filetype = "";
3818         $filename = "";
3819         $filesize = 0;
3820
3821         if (is_array($media)) {
3822                 if (is_array($media['tmp_name'])) {
3823                         $src = $media['tmp_name'][0];
3824                 } else {
3825                         $src = $media['tmp_name'];
3826                 }
3827                 if (is_array($media['name'])) {
3828                         $filename = basename($media['name'][0]);
3829                 } else {
3830                         $filename = basename($media['name']);
3831                 }
3832                 if (is_array($media['size'])) {
3833                         $filesize = intval($media['size'][0]);
3834                 } else {
3835                         $filesize = intval($media['size']);
3836                 }
3837                 if (is_array($media['type'])) {
3838                         $filetype = $media['type'][0];
3839                 } else {
3840                         $filetype = $media['type'];
3841                 }
3842         }
3843
3844         $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
3845
3846         logger::info(
3847                 "File upload src: " . $src . " - filename: " . $filename .
3848                 " - size: " . $filesize . " - type: " . $filetype);
3849
3850         // check if there was a php upload error
3851         if ($filesize == 0 && $media['error'] == 1) {
3852                 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3853         }
3854         // check against max upload size within Friendica instance
3855         $maximagesize = DI::config()->get('system', 'maximagesize');
3856         if ($maximagesize && ($filesize > $maximagesize)) {
3857                 $formattedBytes = Strings::formatBytes($maximagesize);
3858                 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3859         }
3860
3861         // create Photo instance with the data of the image
3862         $imagedata = @file_get_contents($src);
3863         $Image = new Image($imagedata, $filetype);
3864         if (!$Image->isValid()) {
3865                 throw new InternalServerErrorException("unable to process image data");
3866         }
3867
3868         // check orientation of image
3869         $Image->orient($src);
3870         @unlink($src);
3871
3872         // check max length of images on server
3873         $max_length = DI::config()->get('system', 'max_image_length');
3874         if ($max_length > 0) {
3875                 $Image->scaleDown($max_length);
3876                 logger::info("File upload: Scaling picture to new size " . $max_length);
3877         }
3878         $width = $Image->getWidth();
3879         $height = $Image->getHeight();
3880
3881         // create a new resource-id if not already provided
3882         $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
3883
3884         if ($mediatype == "photo") {
3885                 // upload normal image (scales 0, 1, 2)
3886                 logger::info("photo upload: starting new photo upload");
3887
3888                 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3889                 if (!$r) {
3890                         logger::notice("photo upload: image upload with scale 0 (original size) failed");
3891                 }
3892                 if ($width > 640 || $height > 640) {
3893                         $Image->scaleDown(640);
3894                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3895                         if (!$r) {
3896                                 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
3897                         }
3898                 }
3899
3900                 if ($width > 320 || $height > 320) {
3901                         $Image->scaleDown(320);
3902                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3903                         if (!$r) {
3904                                 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
3905                         }
3906                 }
3907                 logger::info("photo upload: new photo upload ended");
3908         } elseif ($mediatype == "profileimage") {
3909                 // upload profile image (scales 4, 5, 6)
3910                 logger::info("photo upload: starting new profile image upload");
3911
3912                 if ($width > 300 || $height > 300) {
3913                         $Image->scaleDown(300);
3914                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3915                         if (!$r) {
3916                                 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
3917                         }
3918                 }
3919
3920                 if ($width > 80 || $height > 80) {
3921                         $Image->scaleDown(80);
3922                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3923                         if (!$r) {
3924                                 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
3925                         }
3926                 }
3927
3928                 if ($width > 48 || $height > 48) {
3929                         $Image->scaleDown(48);
3930                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3931                         if (!$r) {
3932                                 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
3933                         }
3934                 }
3935                 $Image->__destruct();
3936                 logger::info("photo upload: new profile image upload ended");
3937         }
3938
3939         if (!empty($r)) {
3940                 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3941                 if ($photo_id == null && $mediatype == "photo") {
3942                         post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
3943                 }
3944                 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3945                 return prepare_photo_data($type, false, $resource_id);
3946         } else {
3947                 throw new InternalServerErrorException("image upload failed");
3948         }
3949 }
3950
3951 /**
3952  *
3953  * @param string  $hash
3954  * @param string  $allow_cid
3955  * @param string  $deny_cid
3956  * @param string  $allow_gid
3957  * @param string  $deny_gid
3958  * @param string  $filetype
3959  * @param boolean $visibility
3960  * @throws InternalServerErrorException
3961  */
3962 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
3963 {
3964         // get data about the api authenticated user
3965         $uri = Item::newURI(intval(api_user()));
3966         $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
3967
3968         $arr = [];
3969         $arr['guid']          = System::createUUID();
3970         $arr['uid']           = intval(api_user());
3971         $arr['uri']           = $uri;
3972         $arr['type']          = 'photo';
3973         $arr['wall']          = 1;
3974         $arr['resource-id']   = $hash;
3975         $arr['contact-id']    = $owner_record['id'];
3976         $arr['owner-name']    = $owner_record['name'];
3977         $arr['owner-link']    = $owner_record['url'];
3978         $arr['owner-avatar']  = $owner_record['thumb'];
3979         $arr['author-name']   = $owner_record['name'];
3980         $arr['author-link']   = $owner_record['url'];
3981         $arr['author-avatar'] = $owner_record['thumb'];
3982         $arr['title']         = "";
3983         $arr['allow_cid']     = $allow_cid;
3984         $arr['allow_gid']     = $allow_gid;
3985         $arr['deny_cid']      = $deny_cid;
3986         $arr['deny_gid']      = $deny_gid;
3987         $arr['visible']       = $visibility;
3988         $arr['origin']        = 1;
3989
3990         $typetoext = [
3991                         'image/jpeg' => 'jpg',
3992                         'image/png' => 'png',
3993                         'image/gif' => 'gif'
3994                         ];
3995
3996         // adds link to the thumbnail scale photo
3997         $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
3998                                 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
3999                                 . '[/url]';
4000
4001         // do the magic for storing the item in the database and trigger the federation to other contacts
4002         Item::insert($arr);
4003 }
4004
4005 /**
4006  *
4007  * @param string $type
4008  * @param int    $scale
4009  * @param string $photo_id
4010  *
4011  * @return array
4012  * @throws BadRequestException
4013  * @throws ForbiddenException
4014  * @throws ImagickException
4015  * @throws InternalServerErrorException
4016  * @throws NotFoundException
4017  * @throws UnauthorizedException
4018  */
4019 function prepare_photo_data($type, $scale, $photo_id)
4020 {
4021         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4022
4023         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4024
4025         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4026         $data_sql = ($scale === false ? "" : "data, ");
4027
4028         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4029         // clients needs to convert this in their way for further processing
4030         $r = DBA::toArray(DBA::p(
4031                 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4032                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4033                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4034                         FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
4035                                    `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4036                                    `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4037                 local_user(),
4038                 $photo_id
4039         ));
4040
4041         $typetoext = [
4042                 'image/jpeg' => 'jpg',
4043                 'image/png' => 'png',
4044                 'image/gif' => 'gif'
4045         ];
4046
4047         // prepare output data for photo
4048         if (DBA::isResult($r)) {
4049                 $data = ['photo' => $r[0]];
4050                 $data['photo']['id'] = $data['photo']['resource-id'];
4051                 if ($scale !== false) {
4052                         $data['photo']['data'] = base64_encode($data['photo']['data']);
4053                 } else {
4054                         unset($data['photo']['datasize']); //needed only with scale param
4055                 }
4056                 if ($type == "xml") {
4057                         $data['photo']['links'] = [];
4058                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4059                                 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4060                                                                                 "scale" => $k,
4061                                                                                 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4062                         }
4063                 } else {
4064                         $data['photo']['link'] = [];
4065                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4066                         $i = 0;
4067                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4068                                 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4069                                 $i++;
4070                         }
4071                 }
4072                 unset($data['photo']['resource-id']);
4073                 unset($data['photo']['minscale']);
4074                 unset($data['photo']['maxscale']);
4075         } else {
4076                 throw new NotFoundException();
4077         }
4078
4079         // retrieve item element for getting activities (like, dislike etc.) related to photo
4080         $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4081         $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4082         if (!DBA::isResult($item)) {
4083                 throw new NotFoundException('Photo-related item not found.');
4084         }
4085
4086         $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4087
4088         // retrieve comments on photo
4089         $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4090                 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4091
4092         $statuses = Post::selectForUser(api_user(), [], $condition);
4093
4094         // prepare output of comments
4095         $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4096         $comments = [];
4097         if ($type == "xml") {
4098                 $k = 0;
4099                 foreach ($commentData as $comment) {
4100                         $comments[$k++ . ":comment"] = $comment;
4101                 }
4102         } else {
4103                 foreach ($commentData as $comment) {
4104                         $comments[] = $comment;
4105                 }
4106         }
4107         $data['photo']['friendica_comments'] = $comments;
4108
4109         // include info if rights on photo and rights on item are mismatching
4110         $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4111                 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4112                 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4113                 $data['photo']['deny_gid'] != $item['deny_gid'];
4114         $data['photo']['rights_mismatch'] = $rights_mismatch;
4115
4116         return $data;
4117 }
4118
4119 /**
4120  * Return an item with announcer data if it had been announced
4121  *
4122  * @param array $item Item array
4123  * @return array Item array with announce data
4124  */
4125 function api_get_announce($item)
4126 {
4127         // Quit if the item already has got a different owner and author
4128         if ($item['owner-id'] != $item['author-id']) {
4129                 return [];
4130         }
4131
4132         // Don't change original or Diaspora posts
4133         if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4134                 return [];
4135         }
4136
4137         // Quit if we do now the original author and it had been a post from a native network
4138         if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4139                 return [];
4140         }
4141
4142         $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4143         $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4144         $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4145         if (!DBA::isResult($announce)) {
4146                 return [];
4147         }
4148
4149         return array_merge($item, $announce);
4150 }
4151
4152 /**
4153  *
4154  * @param array $item
4155  *
4156  * @return array
4157  * @throws Exception
4158  */
4159 function api_in_reply_to($item)
4160 {
4161         $in_reply_to = [];
4162
4163         $in_reply_to['status_id'] = null;
4164         $in_reply_to['user_id'] = null;
4165         $in_reply_to['status_id_str'] = null;
4166         $in_reply_to['user_id_str'] = null;
4167         $in_reply_to['screen_name'] = null;
4168
4169         if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4170                 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4171                 if (DBA::isResult($parent)) {
4172                         $in_reply_to['status_id'] = intval($parent['id']);
4173                 } else {
4174                         $in_reply_to['status_id'] = intval($item['parent']);
4175                 }
4176
4177                 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4178
4179                 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4180                 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4181
4182                 if (DBA::isResult($parent)) {
4183                         $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4184                         $in_reply_to['user_id'] = intval($parent['author-id']);
4185                         $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4186                 }
4187
4188                 // There seems to be situation, where both fields are identical:
4189                 // https://github.com/friendica/friendica/issues/1010
4190                 // This is a bugfix for that.
4191                 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4192                         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']]);
4193                         $in_reply_to['status_id'] = null;
4194                         $in_reply_to['user_id'] = null;
4195                         $in_reply_to['status_id_str'] = null;
4196                         $in_reply_to['user_id_str'] = null;
4197                         $in_reply_to['screen_name'] = null;
4198                 }
4199         }
4200
4201         return $in_reply_to;
4202 }
4203
4204 /**
4205  *
4206  * @param string $text
4207  *
4208  * @return string
4209  * @throws InternalServerErrorException
4210  */
4211 function api_clean_plain_items($text)
4212 {
4213         $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4214
4215         $text = BBCode::cleanPictureLinks($text);
4216         $URLSearchString = "^\[\]";
4217
4218         $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4219
4220         if ($include_entities == "true") {
4221                 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4222         }
4223
4224         // Simplify "attachment" element
4225         $text = BBCode::removeAttachment($text);
4226
4227         return $text;
4228 }
4229
4230 /**
4231  *
4232  * @param array $contacts
4233  *
4234  * @return void
4235  */
4236 function api_best_nickname(&$contacts)
4237 {
4238         $best_contact = [];
4239
4240         if (count($contacts) == 0) {
4241                 return;
4242         }
4243
4244         foreach ($contacts as $contact) {
4245                 if ($contact["network"] == "") {
4246                         $contact["network"] = "dfrn";
4247                         $best_contact = [$contact];
4248                 }
4249         }
4250
4251         if (sizeof($best_contact) == 0) {
4252                 foreach ($contacts as $contact) {
4253                         if ($contact["network"] == "dfrn") {
4254                                 $best_contact = [$contact];
4255                         }
4256                 }
4257         }
4258
4259         if (sizeof($best_contact) == 0) {
4260                 foreach ($contacts as $contact) {
4261                         if ($contact["network"] == "dspr") {
4262                                 $best_contact = [$contact];
4263                         }
4264                 }
4265         }
4266
4267         if (sizeof($best_contact) == 0) {
4268                 foreach ($contacts as $contact) {
4269                         if ($contact["network"] == "stat") {
4270                                 $best_contact = [$contact];
4271                         }
4272                 }
4273         }
4274
4275         if (sizeof($best_contact) == 0) {
4276                 foreach ($contacts as $contact) {
4277                         if ($contact["network"] == "pump") {
4278                                 $best_contact = [$contact];
4279                         }
4280                 }
4281         }
4282
4283         if (sizeof($best_contact) == 0) {
4284                 foreach ($contacts as $contact) {
4285                         if ($contact["network"] == "twit") {
4286                                 $best_contact = [$contact];
4287                         }
4288                 }
4289         }
4290
4291         if (sizeof($best_contact) == 1) {
4292                 $contacts = $best_contact;
4293         } else {
4294                 $contacts = [$contacts[0]];
4295         }
4296 }
4297
4298 /**
4299  * Return all or a specified group of the user with the containing contacts.
4300  *
4301  * @param string $type Return type (atom, rss, xml, json)
4302  *
4303  * @return array|string
4304  * @throws BadRequestException
4305  * @throws ForbiddenException
4306  * @throws ImagickException
4307  * @throws InternalServerErrorException
4308  * @throws UnauthorizedException
4309  */
4310 function api_friendica_group_show($type)
4311 {
4312         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4313
4314         // params
4315         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4316         $gid = $_REQUEST['gid'] ?? 0;
4317         $uid = $user_info['uid'];
4318
4319         // get data of the specified group id or all groups if not specified
4320         if ($gid != 0) {
4321                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
4322
4323                 // error message if specified gid is not in database
4324                 if (!DBA::isResult($groups)) {
4325                         throw new BadRequestException("gid not available");
4326                 }
4327         } else {
4328                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
4329         }
4330
4331         // loop through all groups and retrieve all members for adding data in the user array
4332         $grps = [];
4333         foreach ($groups as $rr) {
4334                 $members = Contact\Group::getById($rr['id']);
4335                 $users = [];
4336
4337                 if ($type == "xml") {
4338                         $user_element = "users";
4339                         $k = 0;
4340                         foreach ($members as $member) {
4341                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
4342                                 $users[$k++.":user"] = $user;
4343                         }
4344                 } else {
4345                         $user_element = "user";
4346                         foreach ($members as $member) {
4347                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
4348                                 $users[] = $user;
4349                         }
4350                 }
4351                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
4352         }
4353         return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
4354 }
4355
4356 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4357
4358 /**
4359  * Delete a group.
4360  *
4361  * @param string $type Return type (atom, rss, xml, json)
4362  *
4363  * @return array|string
4364  * @throws BadRequestException
4365  * @throws ForbiddenException
4366  * @throws ImagickException
4367  * @throws InternalServerErrorException
4368  * @throws UnauthorizedException
4369  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
4370  */
4371 function api_lists_destroy($type)
4372 {
4373         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4374
4375         // params
4376         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4377         $gid = $_REQUEST['list_id'] ?? 0;
4378         $uid = $user_info['uid'];
4379
4380         // error if no gid specified
4381         if ($gid == 0) {
4382                 throw new BadRequestException('gid not specified');
4383         }
4384
4385         // get data of the specified group id
4386         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4387         // error message if specified gid is not in database
4388         if (!$group) {
4389                 throw new BadRequestException('gid not available');
4390         }
4391
4392         if (Group::remove($gid)) {
4393                 $list = [
4394                         'name' => $group['name'],
4395                         'id' => intval($gid),
4396                         'id_str' => (string) $gid,
4397                         'user' => $user_info
4398                 ];
4399
4400                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4401         }
4402 }
4403
4404 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
4405
4406 /**
4407  * Add a new group to the database.
4408  *
4409  * @param  string $name  Group name
4410  * @param  int    $uid   User ID
4411  * @param  array  $users List of users to add to the group
4412  *
4413  * @return array
4414  * @throws BadRequestException
4415  */
4416 function group_create($name, $uid, $users = [])
4417 {
4418         // error if no name specified
4419         if ($name == "") {
4420                 throw new BadRequestException('group name not specified');
4421         }
4422
4423         // error message if specified group name already exists
4424         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
4425                 throw new BadRequestException('group name already exists');
4426         }
4427
4428         // Check if the group needs to be reactivated
4429         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
4430                 $reactivate_group = true;
4431         }
4432
4433         // create group
4434         $ret = Group::create($uid, $name);
4435         if ($ret) {
4436                 $gid = Group::getIdByName($uid, $name);
4437         } else {
4438                 throw new BadRequestException('other API error');
4439         }
4440
4441         // add members
4442         $erroraddinguser = false;
4443         $errorusers = [];
4444         foreach ($users as $user) {
4445                 $cid = $user['cid'];
4446                 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4447                         Group::addMember($gid, $cid);
4448                 } else {
4449                         $erroraddinguser = true;
4450                         $errorusers[] = $cid;
4451                 }
4452         }
4453
4454         // return success message incl. missing users in array
4455         $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
4456
4457         return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4458 }
4459
4460 /**
4461  * Create the specified group with the posted array of contacts.
4462  *
4463  * @param string $type Return type (atom, rss, xml, json)
4464  *
4465  * @return array|string
4466  * @throws BadRequestException
4467  * @throws ForbiddenException
4468  * @throws ImagickException
4469  * @throws InternalServerErrorException
4470  * @throws UnauthorizedException
4471  */
4472 function api_friendica_group_create($type)
4473 {
4474         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4475
4476         // params
4477         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4478         $name = $_REQUEST['name'] ?? '';
4479         $uid = $user_info['uid'];
4480         $json = json_decode($_POST['json'], true);
4481         $users = $json['user'];
4482
4483         $success = group_create($name, $uid, $users);
4484
4485         return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
4486 }
4487
4488 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4489
4490 /**
4491  * Create a new group.
4492  *
4493  * @param string $type Return type (atom, rss, xml, json)
4494  *
4495  * @return array|string
4496  * @throws BadRequestException
4497  * @throws ForbiddenException
4498  * @throws ImagickException
4499  * @throws InternalServerErrorException
4500  * @throws UnauthorizedException
4501  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
4502  */
4503 function api_lists_create($type)
4504 {
4505         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4506
4507         // params
4508         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4509         $name = $_REQUEST['name'] ?? '';
4510         $uid = $user_info['uid'];
4511
4512         $success = group_create($name, $uid);
4513         if ($success['success']) {
4514                 $grp = [
4515                         'name' => $success['name'],
4516                         'id' => intval($success['gid']),
4517                         'id_str' => (string) $success['gid'],
4518                         'user' => $user_info
4519                 ];
4520
4521                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
4522         }
4523 }
4524
4525 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4526
4527 /**
4528  * Update the specified group with the posted array of contacts.
4529  *
4530  * @param string $type Return type (atom, rss, xml, json)
4531  *
4532  * @return array|string
4533  * @throws BadRequestException
4534  * @throws ForbiddenException
4535  * @throws ImagickException
4536  * @throws InternalServerErrorException
4537  * @throws UnauthorizedException
4538  */
4539 function api_friendica_group_update($type)
4540 {
4541         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4542
4543         // params
4544         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4545         $uid = $user_info['uid'];
4546         $gid = $_REQUEST['gid'] ?? 0;
4547         $name = $_REQUEST['name'] ?? '';
4548         $json = json_decode($_POST['json'], true);
4549         $users = $json['user'];
4550
4551         // error if no name specified
4552         if ($name == "") {
4553                 throw new BadRequestException('group name not specified');
4554         }
4555
4556         // error if no gid specified
4557         if ($gid == "") {
4558                 throw new BadRequestException('gid not specified');
4559         }
4560
4561         // remove members
4562         $members = Contact\Group::getById($gid);
4563         foreach ($members as $member) {
4564                 $cid = $member['id'];
4565                 foreach ($users as $user) {
4566                         $found = ($user['cid'] == $cid ? true : false);
4567                 }
4568                 if (!isset($found) || !$found) {
4569                         $gid = Group::getIdByName($uid, $name);
4570                         Group::removeMember($gid, $cid);
4571                 }
4572         }
4573
4574         // add members
4575         $erroraddinguser = false;
4576         $errorusers = [];
4577         foreach ($users as $user) {
4578                 $cid = $user['cid'];
4579
4580                 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4581                         Group::addMember($gid, $cid);
4582                 } else {
4583                         $erroraddinguser = true;
4584                         $errorusers[] = $cid;
4585                 }
4586         }
4587
4588         // return success message incl. missing users in array
4589         $status = ($erroraddinguser ? "missing user" : "ok");
4590         $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4591         return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
4592 }
4593
4594 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4595
4596 /**
4597  * Update information about a group.
4598  *
4599  * @param string $type Return type (atom, rss, xml, json)
4600  *
4601  * @return array|string
4602  * @throws BadRequestException
4603  * @throws ForbiddenException
4604  * @throws ImagickException
4605  * @throws InternalServerErrorException
4606  * @throws UnauthorizedException
4607  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4608  */
4609 function api_lists_update($type)
4610 {
4611         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4612
4613         // params
4614         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4615         $gid = $_REQUEST['list_id'] ?? 0;
4616         $name = $_REQUEST['name'] ?? '';
4617         $uid = $user_info['uid'];
4618
4619         // error if no gid specified
4620         if ($gid == 0) {
4621                 throw new BadRequestException('gid not specified');
4622         }
4623
4624         // get data of the specified group id
4625         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4626         // error message if specified gid is not in database
4627         if (!$group) {
4628                 throw new BadRequestException('gid not available');
4629         }
4630
4631         if (Group::update($gid, $name)) {
4632                 $list = [
4633                         'name' => $name,
4634                         'id' => intval($gid),
4635                         'id_str' => (string) $gid,
4636                         'user' => $user_info
4637                 ];
4638
4639                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4640         }
4641 }
4642
4643 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4644
4645 /**
4646  * Set notification as seen and returns associated item (if possible)
4647  *
4648  * POST request with 'id' param as notification id
4649  *
4650  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4651  * @return string|array
4652  * @throws BadRequestException
4653  * @throws ForbiddenException
4654  * @throws ImagickException
4655  * @throws InternalServerErrorException
4656  * @throws UnauthorizedException
4657  */
4658 function api_friendica_notification_seen($type)
4659 {
4660         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4661
4662         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4663
4664         if (DI::args()->getArgc() !== 4) {
4665                 throw new BadRequestException('Invalid argument count');
4666         }
4667
4668         $id = intval($_REQUEST['id'] ?? 0);
4669
4670         try {
4671                 $Notify = DI::notify()->selectOneById($id);
4672                 if ($Notify->uid !== api_user()) {
4673                         throw new NotFoundException();
4674                 }
4675
4676                 if ($Notify->uriId) {
4677                         DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
4678                 }
4679
4680                 $Notify->setSeen();
4681                 DI::notify()->save($Notify);
4682
4683                 if ($Notify->otype === Notification\ObjectType::ITEM) {
4684                         $item = Post::selectFirstForUser(api_user(), [], ['id' => $Notify->iid, 'uid' => api_user()]);
4685                         if (DBA::isResult($item)) {
4686                                 // we found the item, return it to the user
4687                                 $ret  = api_format_items([$item], $user_info, false, $type);
4688                                 $data = ['status' => $ret];
4689                                 return DI::apiResponse()->formatData('status', $type, $data);
4690                         }
4691                         // the item can't be found, but we set the notification as seen, so we count this as a success
4692                 }
4693
4694                 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
4695         } catch (NotFoundException $e) {
4696                 throw new BadRequestException('Invalid argument', $e);
4697         } catch (Exception $e) {
4698                 throw new InternalServerErrorException('Internal Server exception', $e);
4699         }
4700 }
4701
4702 /// @TODO move to top of file or somewhere better
4703 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4704
4705 /**
4706  * search for direct_messages containing a searchstring through api
4707  *
4708  * @param string $type      Known types are 'atom', 'rss', 'xml' and 'json'
4709  * @param string $box
4710  * @return string|array (success: success=true if found and search_result contains found messages,
4711  *                          success=false if nothing was found, search_result='nothing found',
4712  *                          error: result=error with error message)
4713  * @throws BadRequestException
4714  * @throws ForbiddenException
4715  * @throws ImagickException
4716  * @throws InternalServerErrorException
4717  * @throws UnauthorizedException
4718  */
4719 function api_friendica_direct_messages_search($type, $box = "")
4720 {
4721         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4722
4723         // params
4724         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4725         $searchstring = $_REQUEST['searchstring'] ?? '';
4726         $uid = $user_info['uid'];
4727
4728         // error if no searchstring specified
4729         if ($searchstring == "") {
4730                 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
4731                 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
4732         }
4733
4734         // get data for the specified searchstring
4735         $r = DBA::toArray(DBA::p(
4736                 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND `body` LIKE ? ORDER BY `mail`.`id` DESC",
4737                 $uid,
4738                 '%'.$searchstring.'%'
4739         ));
4740
4741         $profile_url = $user_info["url"];
4742
4743         // message if nothing was found
4744         if (!DBA::isResult($r)) {
4745                 $success = ['success' => false, 'search_results' => 'problem with query'];
4746         } elseif (count($r) == 0) {
4747                 $success = ['success' => false, 'search_results' => 'nothing found'];
4748         } else {
4749                 $ret = [];
4750                 foreach ($r as $item) {
4751                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
4752                                 $recipient = $user_info;
4753                                 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4754                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4755                                 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4756                                 $sender = $user_info;
4757                         }
4758
4759                         if (isset($recipient) && isset($sender)) {
4760                                 $ret[] = api_format_messages($item, $recipient, $sender);
4761                         }
4762                 }
4763                 $success = ['success' => true, 'search_results' => $ret];
4764         }
4765
4766         return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
4767 }
4768
4769 /// @TODO move to top of file or somewhere better
4770 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4771
4772 /*
4773  * Number of comments
4774  *
4775  * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
4776  *
4777  * @param object $data [Status, Status]
4778  *
4779  * @return void
4780  */
4781 function bindComments(&$data)
4782 {
4783         if (count($data) == 0) {
4784                 return;
4785         }
4786
4787         $ids = [];
4788         $comments = [];
4789         foreach ($data as $item) {
4790                 $ids[] = $item['id'];
4791         }
4792
4793         $idStr = DBA::escape(implode(', ', $ids));
4794         $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
4795         $items = DBA::p($sql, 0, GRAVITY_COMMENT);
4796         $itemsData = DBA::toArray($items);
4797
4798         foreach ($itemsData as $item) {
4799                 $comments[$item['parent']] = $item['comments'];
4800         }
4801
4802         foreach ($data as $idx => $item) {
4803                 $id = $item['id'];
4804                 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
4805         }
4806 }
4807
4808 /*
4809 @TODO Maybe open to implement?
4810 To.Do:
4811         [pagename] => api/1.1/statuses/lookup.json
4812         [id] => 605138389168451584
4813         [include_cards] => true
4814         [cards_platform] => Android-12
4815         [include_entities] => true
4816         [include_my_retweet] => 1
4817         [include_rts] => 1
4818         [include_reply_count] => true
4819         [include_descendent_reply_count] => true
4820 (?)
4821
4822
4823 Not implemented by now:
4824 statuses/retweets_of_me
4825 friendships/create
4826 friendships/destroy
4827 friendships/exists
4828 friendships/show
4829 account/update_location
4830 account/update_profile_background_image
4831 blocks/create
4832 blocks/destroy
4833 friendica/profile/update
4834 friendica/profile/create
4835 friendica/profile/delete
4836
4837 Not implemented in status.net:
4838 statuses/retweeted_to_me
4839 statuses/retweeted_by_me
4840 direct_messages/destroy
4841 account/end_session
4842 account/update_delivery_device
4843 notifications/follow
4844 notifications/leave
4845 blocks/exists
4846 blocks/blocking
4847 lists
4848 */