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