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