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