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