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