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