3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\System;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Group;
36 use Friendica\Model\Item;
37 use Friendica\Model\Mail;
38 use Friendica\Model\Notification;
39 use Friendica\Model\Photo;
40 use Friendica\Model\Post;
41 use Friendica\Model\Profile;
42 use Friendica\Model\User;
43 use Friendica\Module\BaseApi;
44 use Friendica\Network\HTTPException;
45 use Friendica\Network\HTTPException\BadRequestException;
46 use Friendica\Network\HTTPException\ForbiddenException;
47 use Friendica\Network\HTTPException\InternalServerErrorException;
48 use Friendica\Network\HTTPException\NotFoundException;
49 use Friendica\Network\HTTPException\TooManyRequestsException;
50 use Friendica\Network\HTTPException\UnauthorizedException;
51 use Friendica\Object\Image;
52 use Friendica\Security\BasicAuth;
53 use Friendica\Util\DateTimeFormat;
54 use Friendica\Util\Images;
55 use Friendica\Util\Network;
56 use Friendica\Util\Strings;
58 require_once __DIR__ . '/../mod/item.php';
59 require_once __DIR__ . '/../mod/wall_upload.php';
61 define('API_METHOD_ANY', '*');
62 define('API_METHOD_GET', 'GET');
63 define('API_METHOD_POST', 'POST,PUT');
64 define('API_METHOD_DELETE', 'POST,DELETE');
66 define('API_LOG_PREFIX', 'API {action} - ');
71 * Register a function to be the endpoint for defined API path.
73 * @param string $path API URL path, relative to DI::baseUrl()
74 * @param string $func Function name to call on path request
75 * @param bool $auth API need logged user
76 * @param string $method HTTP method reqiured to call this endpoint.
77 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
78 * Default to API_METHOD_ANY
80 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
90 // Workaround for hotot
91 $path = str_replace("api/", "api/1.1/", $path);
101 * Main API entry point
103 * Authenticate user, call registered API function, set HTTP headers
106 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
107 * @return string|array API call result
110 function api_call(App $a, App\Arguments $args = null)
119 if (strpos($args->getCommand(), ".xml") > 0) {
122 if (strpos($args->getCommand(), ".json") > 0) {
125 if (strpos($args->getCommand(), ".rss") > 0) {
128 if (strpos($args->getCommand(), ".atom") > 0) {
133 foreach ($API as $p => $info) {
134 if (strpos($args->getCommand(), $p) === 0) {
135 if (!empty($info['auth']) && BaseApi::getCurrentUserID() === false) {
136 BasicAuth::getCurrentUserID(true);
137 Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
140 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
142 $stamp = microtime(true);
143 $return = call_user_func($info['func'], $type);
144 $duration = floatval(microtime(true) - $stamp);
146 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
148 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
150 if (false === $return) {
152 * api function returned false withour throw an
153 * exception. This should not happend, throw a 500
155 throw new InternalServerErrorException();
160 header("Content-Type: text/xml");
163 header("Content-Type: application/json");
164 if (!empty($return)) {
165 $json = json_encode(end($return));
166 if (!empty($_GET['callback'])) {
167 $json = $_GET['callback'] . "(" . $json . ")";
173 header("Content-Type: application/rss+xml");
174 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
177 header("Content-Type: application/atom+xml");
178 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
185 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
186 throw new NotFoundException();
187 } catch (HTTPException $e) {
188 Logger::notice(API_LOG_PREFIX . 'got exception', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString(), 'error' => $e]);
189 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
196 * @param array $recipient
197 * @param array $sender
200 * @throws InternalServerErrorException
202 function api_format_messages($item, $recipient, $sender)
204 // standard meta information
207 'sender_id' => $sender['id'],
209 'recipient_id' => $recipient['id'],
210 'created_at' => DateTimeFormat::utc($item['created'] ?? 'now', DateTimeFormat::API),
211 'sender_screen_name' => $sender['screen_name'],
212 'recipient_screen_name' => $recipient['screen_name'],
214 'recipient' => $recipient,
216 'friendica_seen' => $item['seen'] ?? 0,
217 'friendica_parent_uri' => $item['parent-uri'] ?? '',
220 // "uid" is only needed for some internal stuff, so remove it from here
221 if (isset($ret['sender']['uid'])) {
222 unset($ret['sender']['uid']);
224 if (isset($ret['recipient']['uid'])) {
225 unset($ret['recipient']['uid']);
228 //don't send title to regular StatusNET requests to avoid confusing these apps
229 if (!empty($_GET['getText'])) {
230 $ret['title'] = $item['title'];
231 if ($_GET['getText'] == 'html') {
232 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
233 } elseif ($_GET['getText'] == 'plain') {
234 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
237 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
239 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
240 unset($ret['sender']);
241 unset($ret['recipient']);
249 * @param string $acl_string
254 function check_acl_input($acl_string, $uid)
256 if (empty($acl_string)) {
260 $contact_not_found = false;
262 // split <x><y><z> into array of cid's
263 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
265 // check for each cid if it is available on server
266 $cid_array = $array[0];
267 foreach ($cid_array as $cid) {
268 $cid = str_replace("<", "", $cid);
269 $cid = str_replace(">", "", $cid);
270 $condition = ['id' => $cid, 'uid' => $uid];
271 $contact_not_found |= !DBA::exists('contact', $condition);
273 return $contact_not_found;
277 * @param string $mediatype
278 * @param array $media
279 * @param string $type
280 * @param string $album
281 * @param string $allow_cid
282 * @param string $deny_cid
283 * @param string $allow_gid
284 * @param string $deny_gid
285 * @param string $desc
286 * @param integer $phototype
287 * @param boolean $visibility
288 * @param string $photo_id
291 * @throws BadRequestException
292 * @throws ForbiddenException
293 * @throws ImagickException
294 * @throws InternalServerErrorException
295 * @throws NotFoundException
296 * @throws UnauthorizedException
298 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype, $visibility, $photo_id, $uid)
306 if (is_array($media)) {
307 if (is_array($media['tmp_name'])) {
308 $src = $media['tmp_name'][0];
310 $src = $media['tmp_name'];
312 if (is_array($media['name'])) {
313 $filename = basename($media['name'][0]);
315 $filename = basename($media['name']);
317 if (is_array($media['size'])) {
318 $filesize = intval($media['size'][0]);
320 $filesize = intval($media['size']);
322 if (is_array($media['type'])) {
323 $filetype = $media['type'][0];
325 $filetype = $media['type'];
329 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
332 "File upload src: " . $src . " - filename: " . $filename .
333 " - size: " . $filesize . " - type: " . $filetype);
335 // check if there was a php upload error
336 if ($filesize == 0 && $media['error'] == 1) {
337 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
339 // check against max upload size within Friendica instance
340 $maximagesize = DI::config()->get('system', 'maximagesize');
341 if ($maximagesize && ($filesize > $maximagesize)) {
342 $formattedBytes = Strings::formatBytes($maximagesize);
343 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
346 // create Photo instance with the data of the image
347 $imagedata = @file_get_contents($src);
348 $Image = new Image($imagedata, $filetype);
349 if (!$Image->isValid()) {
350 throw new InternalServerErrorException("unable to process image data");
353 // check orientation of image
354 $Image->orient($src);
357 // check max length of images on server
358 $max_length = DI::config()->get('system', 'max_image_length');
359 if ($max_length > 0) {
360 $Image->scaleDown($max_length);
361 logger::info("File upload: Scaling picture to new size " . $max_length);
363 $width = $Image->getWidth();
364 $height = $Image->getHeight();
366 // create a new resource-id if not already provided
367 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
369 if ($mediatype == "photo") {
370 // upload normal image (scales 0, 1, 2)
371 logger::info("photo upload: starting new photo upload");
373 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
375 logger::notice("photo upload: image upload with scale 0 (original size) failed");
377 if ($width > 640 || $height > 640) {
378 $Image->scaleDown(640);
379 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
381 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
385 if ($width > 320 || $height > 320) {
386 $Image->scaleDown(320);
387 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
389 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
392 logger::info("photo upload: new photo upload ended");
393 } elseif ($mediatype == "profileimage") {
394 // upload profile image (scales 4, 5, 6)
395 logger::info("photo upload: starting new profile image upload");
397 if ($width > 300 || $height > 300) {
398 $Image->scaleDown(300);
399 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
401 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
405 if ($width > 80 || $height > 80) {
406 $Image->scaleDown(80);
407 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
409 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
413 if ($width > 48 || $height > 48) {
414 $Image->scaleDown(48);
415 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
417 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
420 $Image->__destruct();
421 logger::info("photo upload: new profile image upload ended");
425 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
426 if ($photo_id == null && $mediatype == "photo") {
427 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid);
429 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
430 return prepare_photo_data($type, false, $resource_id, $uid);
432 throw new InternalServerErrorException("image upload failed");
438 * @param string $hash
439 * @param string $allow_cid
440 * @param string $deny_cid
441 * @param string $allow_gid
442 * @param string $deny_gid
443 * @param string $filetype
444 * @param boolean $visibility
446 * @throws InternalServerErrorException
448 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid)
450 // get data about the api authenticated user
451 $uri = Item::newURI(intval($uid));
452 $owner_record = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
455 $arr['guid'] = System::createUUID();
456 $arr['uid'] = intval($uid);
458 $arr['type'] = 'photo';
460 $arr['resource-id'] = $hash;
461 $arr['contact-id'] = $owner_record['id'];
462 $arr['owner-name'] = $owner_record['name'];
463 $arr['owner-link'] = $owner_record['url'];
464 $arr['owner-avatar'] = $owner_record['thumb'];
465 $arr['author-name'] = $owner_record['name'];
466 $arr['author-link'] = $owner_record['url'];
467 $arr['author-avatar'] = $owner_record['thumb'];
469 $arr['allow_cid'] = $allow_cid;
470 $arr['allow_gid'] = $allow_gid;
471 $arr['deny_cid'] = $deny_cid;
472 $arr['deny_gid'] = $deny_gid;
473 $arr['visible'] = $visibility;
477 'image/jpeg' => 'jpg',
478 'image/png' => 'png',
482 // adds link to the thumbnail scale photo
483 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
484 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
487 // do the magic for storing the item in the database and trigger the federation to other contacts
493 * @param string $type
495 * @param string $photo_id
498 * @throws BadRequestException
499 * @throws ForbiddenException
500 * @throws ImagickException
501 * @throws InternalServerErrorException
502 * @throws NotFoundException
503 * @throws UnauthorizedException
505 function prepare_photo_data($type, $scale, $photo_id, $uid)
507 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
508 $data_sql = ($scale === false ? "" : "data, ");
510 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
511 // clients needs to convert this in their way for further processing
512 $r = DBA::toArray(DBA::p(
513 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
514 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
515 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
516 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
517 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
518 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
524 'image/jpeg' => 'jpg',
525 'image/png' => 'png',
529 // prepare output data for photo
530 if (DBA::isResult($r)) {
531 $data = ['photo' => $r[0]];
532 $data['photo']['id'] = $data['photo']['resource-id'];
533 if ($scale !== false) {
534 $data['photo']['data'] = base64_encode($data['photo']['data']);
536 unset($data['photo']['datasize']); //needed only with scale param
538 if ($type == "xml") {
539 $data['photo']['links'] = [];
540 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
541 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
543 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
546 $data['photo']['link'] = [];
547 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
549 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
550 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
554 unset($data['photo']['resource-id']);
555 unset($data['photo']['minscale']);
556 unset($data['photo']['maxscale']);
558 throw new NotFoundException();
561 // retrieve item element for getting activities (like, dislike etc.) related to photo
562 $condition = ['uid' => $uid, 'resource-id' => $photo_id];
563 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
564 if (!DBA::isResult($item)) {
565 throw new NotFoundException('Photo-related item not found.');
568 $data['photo']['friendica_activities'] = DI::friendicaActivities()->createFromUriId($item['uri-id'], $item['uid'], $type);
570 // retrieve comments on photo
571 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
572 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
574 $statuses = Post::selectForUser($uid, [], $condition);
576 // prepare output of comments
578 while ($status = DBA::fetch($statuses)) {
579 $commentData[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'])->toArray();
581 DBA::close($statuses);
584 if ($type == "xml") {
586 foreach ($commentData as $comment) {
587 $comments[$k++ . ":comment"] = $comment;
590 foreach ($commentData as $comment) {
591 $comments[] = $comment;
594 $data['photo']['friendica_comments'] = $comments;
596 // include info if rights on photo and rights on item are mismatching
597 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
598 $data['photo']['deny_cid'] != $item['deny_cid'] ||
599 $data['photo']['allow_gid'] != $item['allow_gid'] ||
600 $data['photo']['deny_gid'] != $item['deny_gid'];
601 $data['photo']['rights_mismatch'] = $rights_mismatch;
608 * @param string $text
611 * @throws InternalServerErrorException
613 function api_clean_plain_items($text)
615 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
617 $text = BBCode::cleanPictureLinks($text);
618 $URLSearchString = "^\[\]";
620 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
622 if ($include_entities == "true") {
623 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
626 // Simplify "attachment" element
627 $text = BBCode::removeAttachment($text);
633 * Add a new group to the database.
635 * @param string $name Group name
636 * @param int $uid User ID
637 * @param array $users List of users to add to the group
640 * @throws BadRequestException
642 function group_create($name, $uid, $users = [])
644 // error if no name specified
646 throw new BadRequestException('group name not specified');
649 // error message if specified group name already exists
650 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
651 throw new BadRequestException('group name already exists');
654 // Check if the group needs to be reactivated
655 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
656 $reactivate_group = true;
660 $ret = Group::create($uid, $name);
662 $gid = Group::getIdByName($uid, $name);
664 throw new BadRequestException('other API error');
668 $erroraddinguser = false;
670 foreach ($users as $user) {
672 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
673 Group::addMember($gid, $cid);
675 $erroraddinguser = true;
676 $errorusers[] = $cid;
680 // return success message incl. missing users in array
681 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
683 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
691 * Deprecated function to upload media.
693 * @param string $type Return type (atom, rss, xml, json)
695 * @return array|string
696 * @throws BadRequestException
697 * @throws ForbiddenException
698 * @throws ImagickException
699 * @throws InternalServerErrorException
700 * @throws UnauthorizedException
702 function api_statuses_mediap($type)
704 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
705 $uid = BaseApi::getCurrentUserID();
709 $_REQUEST['profile_uid'] = $uid;
710 $_REQUEST['api_source'] = true;
711 $txt = $_REQUEST['status'] ?? '';
713 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
714 $txt = HTML::toBBCodeVideo($txt);
715 $config = HTMLPurifier_Config::createDefault();
716 $config->set('Cache.DefinitionImpl', null);
717 $purifier = new HTMLPurifier($config);
718 $txt = $purifier->purify($txt);
720 $txt = HTML::toBBCode($txt);
722 $picture = wall_upload_post($a, false);
724 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
725 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
726 $item_id = item_post($a);
728 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
730 // output the post that we just posted.
731 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
732 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
735 /// @TODO move this to top of file or somewhere better!
736 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
739 * Updates the user’s current status.
741 * @param string $type Return type (atom, rss, xml, json)
743 * @return array|string
744 * @throws BadRequestException
745 * @throws ForbiddenException
746 * @throws ImagickException
747 * @throws InternalServerErrorException
748 * @throws TooManyRequestsException
749 * @throws UnauthorizedException
750 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
752 function api_statuses_update($type)
754 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
755 $uid = BaseApi::getCurrentUserID();
759 // convert $_POST array items to the form we use for web posts.
760 if (!empty($_REQUEST['htmlstatus'])) {
761 $txt = $_REQUEST['htmlstatus'];
762 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
763 $txt = HTML::toBBCodeVideo($txt);
765 $config = HTMLPurifier_Config::createDefault();
766 $config->set('Cache.DefinitionImpl', null);
768 $purifier = new HTMLPurifier($config);
769 $txt = $purifier->purify($txt);
771 $_REQUEST['body'] = HTML::toBBCode($txt);
774 $_REQUEST['body'] = $_REQUEST['status'] ?? null;
777 $_REQUEST['title'] = $_REQUEST['title'] ?? null;
779 $parent = $_REQUEST['in_reply_to_status_id'] ?? null;
781 // Twidere sends "-1" if it is no reply ...
786 if (ctype_digit($parent)) {
787 $_REQUEST['parent'] = $parent;
789 $_REQUEST['parent_uri'] = $parent;
792 if (!empty($_REQUEST['lat']) && !empty($_REQUEST['long'])) {
793 $_REQUEST['coord'] = sprintf("%s %s", $_REQUEST['lat'], $_REQUEST['long']);
795 $_REQUEST['profile_uid'] = $uid;
798 // Check for throttling (maximum posts per day, week and month)
799 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
800 if ($throttle_day > 0) {
801 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
803 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
804 $posts_day = Post::count($condition);
806 if ($posts_day > $throttle_day) {
807 logger::info('Daily posting limit reached for user ' . $uid);
808 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
809 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));
813 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
814 if ($throttle_week > 0) {
815 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
817 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
818 $posts_week = Post::count($condition);
820 if ($posts_week > $throttle_week) {
821 logger::info('Weekly posting limit reached for user ' . $uid);
822 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
823 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));
827 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
828 if ($throttle_month > 0) {
829 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
831 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
832 $posts_month = Post::count($condition);
834 if ($posts_month > $throttle_month) {
835 logger::info('Monthly posting limit reached for user ' . $uid);
836 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
837 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));
842 if (!empty($_REQUEST['media_ids'])) {
843 $ids = explode(',', $_REQUEST['media_ids']);
844 } elseif (!empty($_FILES['media'])) {
845 // upload the image if we have one
846 $picture = wall_upload_post($a, false);
847 if (is_array($picture)) {
848 $ids[] = $picture['id'];
856 foreach ($ids as $id) {
857 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
858 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
859 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
860 ORDER BY `photo`.`width` DESC LIMIT 2", $id, $uid));
862 if (!empty($media)) {
863 $ressources[] = $media[0]['resource-id'];
864 $phototypes = Images::supportedTypes();
865 $ext = $phototypes[$media[0]['type']];
867 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
868 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
869 'size' => $media[0]['datasize'],
870 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
871 'description' => $media[0]['desc'] ?? '',
872 'width' => $media[0]['width'],
873 'height' => $media[0]['height']];
875 if (count($media) > 1) {
876 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
877 $attachment['preview-width'] = $media[1]['width'];
878 $attachment['preview-height'] = $media[1]['height'];
880 $attachments[] = $attachment;
884 // We have to avoid that the post is rejected because of an empty body
885 if (empty($_REQUEST['body'])) {
886 $_REQUEST['body'] = '[hr]';
890 if (!empty($attachments)) {
891 $_REQUEST['attachments'] = $attachments;
894 // set this so that the item_post() function is quiet and doesn't redirect or emit json
896 $_REQUEST['api_source'] = true;
898 if (empty($_REQUEST['source'])) {
899 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
902 // call out normal post function
903 $item_id = item_post($a);
905 if (!empty($ressources) && !empty($item_id)) {
906 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
907 foreach ($ressources as $ressource) {
908 Photo::setPermissionForRessource($ressource, $uid, $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
912 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
914 // output the post that we just posted.
915 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
916 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
919 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
920 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
923 * Uploads an image to Friendica.
926 * @throws BadRequestException
927 * @throws ForbiddenException
928 * @throws ImagickException
929 * @throws InternalServerErrorException
930 * @throws UnauthorizedException
931 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
933 function api_media_upload()
935 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
937 if (empty($_FILES['media'])) {
939 throw new BadRequestException("No media.");
942 $media = wall_upload_post(DI::app(), false);
945 throw new InternalServerErrorException();
949 $returndata["media_id"] = $media["id"];
950 $returndata["media_id_string"] = (string)$media["id"];
951 $returndata["size"] = $media["size"];
952 $returndata["image"] = ["w" => $media["width"],
953 "h" => $media["height"],
954 "image_type" => $media["type"],
955 "friendica_preview_url" => $media["preview"]];
957 Logger::info('Media uploaded', ['return' => $returndata]);
959 return ["media" => $returndata];
962 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
965 * Updates media meta data (picture descriptions)
967 * @param string $type Return type (atom, rss, xml, json)
969 * @return array|string
970 * @throws BadRequestException
971 * @throws ForbiddenException
972 * @throws ImagickException
973 * @throws InternalServerErrorException
974 * @throws TooManyRequestsException
975 * @throws UnauthorizedException
976 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
978 * @todo Compare the corresponding Twitter function for correct return values
980 function api_media_metadata_create($type)
982 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
983 $uid = BaseApi::getCurrentUserID();
985 $postdata = Network::postdata();
987 if (empty($postdata)) {
988 throw new BadRequestException("No post data");
991 $data = json_decode($postdata, true);
993 throw new BadRequestException("Invalid post data");
996 if (empty($data['media_id']) || empty($data['alt_text'])) {
997 throw new BadRequestException("Missing post data values");
1000 if (empty($data['alt_text']['text'])) {
1001 throw new BadRequestException("No alt text.");
1004 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1006 $condition = ['id' => $data['media_id'], 'uid' => $uid];
1007 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1008 if (!DBA::isResult($photo)) {
1009 throw new BadRequestException("Metadata not found.");
1012 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1015 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1018 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1019 * The author's most recent status will be returned inline.
1021 * @param string $type Return type (atom, rss, xml, json)
1022 * @return array|string
1023 * @throws BadRequestException
1024 * @throws ImagickException
1025 * @throws InternalServerErrorException
1026 * @throws UnauthorizedException
1027 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1029 function api_users_show($type)
1031 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1032 $uid = BaseApi::getCurrentUserID();
1034 $user_info = DI::twitterUser()->createFromUserId($uid, false)->toArray();
1036 // "uid" is only needed for some internal stuff, so remove it from here
1037 unset($user_info['uid']);
1039 return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
1042 api_register_func('api/users/show', 'api_users_show');
1043 api_register_func('api/externalprofile/show', 'api_users_show');
1046 * Search a public user account.
1048 * @param string $type Return type (atom, rss, xml, json)
1050 * @return array|string
1051 * @throws BadRequestException
1052 * @throws ImagickException
1053 * @throws InternalServerErrorException
1054 * @throws UnauthorizedException
1055 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1057 function api_users_search($type)
1059 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1060 $uid = BaseApi::getCurrentUserID();
1064 if (!empty($_GET['q'])) {
1065 $contacts = Contact::selectToArray(
1068 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1076 if (DBA::isResult($contacts)) {
1078 foreach ($contacts as $contact) {
1079 $user_info = DI::twitterUser()->createFromContactId($contact['id'], $uid, false)->toArray();
1081 if ($type == 'xml') {
1082 $userlist[$k++ . ':user'] = $user_info;
1084 $userlist[] = $user_info;
1087 $userlist = ['users' => $userlist];
1089 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1092 throw new BadRequestException('No search term specified.');
1095 return DI::apiResponse()->formatData('users', $type, $userlist);
1098 api_register_func('api/users/search', 'api_users_search');
1101 * Return user objects
1103 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1105 * @param string $type Return format: json or xml
1107 * @return array|string
1108 * @throws BadRequestException
1109 * @throws ImagickException
1110 * @throws InternalServerErrorException
1111 * @throws NotFoundException if the results are empty.
1112 * @throws UnauthorizedException
1114 function api_users_lookup($type)
1116 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1117 $uid = BaseApi::getCurrentUserID();
1121 if (!empty($_REQUEST['user_id'])) {
1122 foreach (explode(',', $_REQUEST['user_id']) as $cid) {
1123 if (!empty($cid) && is_numeric($cid)) {
1124 $users[] = DI::twitterUser()->createFromContactId((int)$cid, $uid, false)->toArray();
1129 if (empty($users)) {
1130 throw new NotFoundException;
1133 return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
1136 api_register_func('api/users/lookup', 'api_users_lookup', true);
1139 * Returns statuses that match a specified query.
1141 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1143 * @param string $type Return format: json, xml, atom, rss
1145 * @return array|string
1146 * @throws BadRequestException if the "q" parameter is missing.
1147 * @throws ForbiddenException
1148 * @throws ImagickException
1149 * @throws InternalServerErrorException
1150 * @throws UnauthorizedException
1152 function api_search($type)
1154 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1155 $uid = BaseApi::getCurrentUserID();
1157 if (empty($_REQUEST['q'])) {
1158 throw new BadRequestException('q parameter is required.');
1161 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1164 $data['status'] = [];
1166 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1167 if (!empty($_REQUEST['rpp'])) {
1168 $count = $_REQUEST['rpp'];
1169 } elseif (!empty($_REQUEST['count'])) {
1170 $count = $_REQUEST['count'];
1173 $since_id = $_REQUEST['since_id'] ?? 0;
1174 $max_id = $_REQUEST['max_id'] ?? 0;
1175 $page = $_REQUEST['page'] ?? 1;
1177 $start = max(0, ($page - 1) * $count);
1179 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1180 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1181 $searchTerm = $matches[1];
1182 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, $uid];
1183 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1185 while ($tag = DBA::fetch($tags)) {
1186 $uriids[] = $tag['uri-id'];
1190 if (empty($uriids)) {
1191 return DI::apiResponse()->formatData('statuses', $type, $data);
1194 $condition = ['uri-id' => $uriids];
1195 if ($exclude_replies) {
1196 $condition['gravity'] = GRAVITY_PARENT;
1199 $params['group_by'] = ['uri-id'];
1201 $condition = ["`id` > ?
1202 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1203 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1204 AND `body` LIKE CONCAT('%',?,'%')",
1205 $since_id, $uid, $_REQUEST['q']];
1207 $condition[0] .= ' AND `id` <= ?';
1208 $condition[] = $max_id;
1214 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1215 $id = Item::fetchByLink($searchTerm, $uid);
1218 $id = Item::fetchByLink($searchTerm);
1222 $statuses = Post::select([], ['id' => $id]);
1226 $statuses = $statuses ?: Post::selectForUser($uid, [], $condition, $params);
1228 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1231 while ($status = DBA::fetch($statuses)) {
1232 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1234 DBA::close($statuses);
1236 $data['status'] = $ret;
1238 return DI::apiResponse()->formatData('statuses', $type, $data);
1241 api_register_func('api/search/tweets', 'api_search', true);
1242 api_register_func('api/search', 'api_search', true);
1245 * Returns a single status.
1247 * @param string $type Return type (atom, rss, xml, json)
1249 * @return array|string
1250 * @throws BadRequestException
1251 * @throws ForbiddenException
1252 * @throws ImagickException
1253 * @throws InternalServerErrorException
1254 * @throws UnauthorizedException
1255 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1257 function api_statuses_show($type)
1259 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1260 $uid = BaseApi::getCurrentUserID();
1263 $id = intval(DI::args()->getArgv()[3] ?? 0);
1266 $id = intval($_REQUEST['id'] ?? 0);
1271 $id = intval(DI::args()->getArgv()[4] ?? 0);
1274 logger::notice('API: api_statuses_show: ' . $id);
1276 $conversation = !empty($_REQUEST['conversation']);
1278 // try to fetch the item for the local user - or the public item, if there is no local one
1279 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1280 if (!DBA::isResult($uri_item)) {
1281 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1284 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1285 if (!DBA::isResult($item)) {
1286 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1291 if ($conversation) {
1292 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1293 $params = ['order' => ['id' => true]];
1295 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1299 $statuses = Post::selectForUser($uid, [], $condition, $params);
1301 /// @TODO How about copying this to above methods which don't check $r ?
1302 if (!DBA::isResult($statuses)) {
1303 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1306 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1309 while ($status = DBA::fetch($statuses)) {
1310 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1312 DBA::close($statuses);
1314 if ($conversation) {
1315 $data = ['status' => $ret];
1316 return DI::apiResponse()->formatData("statuses", $type, $data);
1318 $data = ['status' => $ret[0]];
1319 return DI::apiResponse()->formatData("status", $type, $data);
1323 api_register_func('api/statuses/show', 'api_statuses_show', true);
1327 * @param string $type Return type (atom, rss, xml, json)
1329 * @return array|string
1330 * @throws BadRequestException
1331 * @throws ForbiddenException
1332 * @throws ImagickException
1333 * @throws InternalServerErrorException
1334 * @throws UnauthorizedException
1335 * @todo nothing to say?
1337 function api_conversation_show($type)
1339 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1340 $uid = BaseApi::getCurrentUserID();
1343 $id = intval(DI::args()->getArgv()[3] ?? 0);
1344 $since_id = intval($_REQUEST['since_id'] ?? 0);
1345 $max_id = intval($_REQUEST['max_id'] ?? 0);
1346 $count = intval($_REQUEST['count'] ?? 20);
1347 $page = intval($_REQUEST['page'] ?? 1);
1349 $start = max(0, ($page - 1) * $count);
1352 $id = intval($_REQUEST['id'] ?? 0);
1357 $id = intval(DI::args()->getArgv()[4] ?? 0);
1360 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1362 // try to fetch the item for the local user - or the public item, if there is no local one
1363 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1364 if (!DBA::isResult($item)) {
1365 throw new BadRequestException("There is no status with the id $id.");
1368 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1369 if (!DBA::isResult($parent)) {
1370 throw new BadRequestException("There is no status with this id.");
1373 $id = $parent['id'];
1375 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1376 $id, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1379 $condition[0] .= " AND `id` <= ?";
1380 $condition[] = $max_id;
1383 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1384 $statuses = Post::selectForUser($uid, [], $condition, $params);
1386 if (!DBA::isResult($statuses)) {
1387 throw new BadRequestException("There is no status with id $id.");
1390 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1393 while ($status = DBA::fetch($statuses)) {
1394 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1396 DBA::close($statuses);
1398 $data = ['status' => $ret];
1399 return DI::apiResponse()->formatData("statuses", $type, $data);
1402 api_register_func('api/conversation/show', 'api_conversation_show', true);
1403 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1408 * @param string $type Return type (atom, rss, xml, json)
1410 * @return array|string
1411 * @throws BadRequestException
1412 * @throws ForbiddenException
1413 * @throws ImagickException
1414 * @throws InternalServerErrorException
1415 * @throws UnauthorizedException
1416 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1418 function api_statuses_repeat($type)
1420 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1421 $uid = BaseApi::getCurrentUserID();
1424 $id = intval(DI::args()->getArgv()[3] ?? 0);
1427 $id = intval($_REQUEST['id'] ?? 0);
1432 $id = intval(DI::args()->getArgv()[4] ?? 0);
1435 logger::notice('API: api_statuses_repeat: ' . $id);
1437 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1438 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1440 if (DBA::isResult($item) && !empty($item['body'])) {
1441 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1442 if (!Item::performActivity($id, 'announce', $uid)) {
1443 throw new InternalServerErrorException();
1448 if (strpos($item['body'], "[/share]") !== false) {
1449 $pos = strpos($item['body'], "[share");
1450 $post = substr($item['body'], $pos);
1452 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1454 if (!empty($item['title'])) {
1455 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1458 $post .= $item['body'];
1459 $post .= "[/share]";
1461 $_REQUEST['body'] = $post;
1462 $_REQUEST['profile_uid'] = $uid;
1463 $_REQUEST['api_source'] = true;
1465 if (empty($_REQUEST['source'])) {
1466 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
1469 $item_id = item_post(DI::app());
1472 throw new ForbiddenException();
1475 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1477 // output the post that we just posted.
1478 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
1479 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
1482 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1485 * Destroys a specific status.
1487 * @param string $type Return type (atom, rss, xml, json)
1489 * @return array|string
1490 * @throws BadRequestException
1491 * @throws ForbiddenException
1492 * @throws ImagickException
1493 * @throws InternalServerErrorException
1494 * @throws UnauthorizedException
1495 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1497 function api_statuses_destroy($type)
1499 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1500 $uid = BaseApi::getCurrentUserID();
1503 $id = intval(DI::args()->getArgv()[3] ?? 0);
1506 $id = intval($_REQUEST['id'] ?? 0);
1511 $id = intval(DI::args()->getArgv()[4] ?? 0);
1514 logger::notice('API: api_statuses_destroy: ' . $id);
1516 $ret = api_statuses_show($type);
1518 Item::deleteForUser(['id' => $id], $uid);
1523 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1526 * Star/unstar an item.
1527 * param: id : id of the item
1529 * @param string $type Return type (atom, rss, xml, json)
1531 * @return array|string
1532 * @throws BadRequestException
1533 * @throws ForbiddenException
1534 * @throws ImagickException
1535 * @throws InternalServerErrorException
1536 * @throws UnauthorizedException
1537 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1539 function api_favorites_create_destroy($type)
1541 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1542 $uid = BaseApi::getCurrentUserID();
1544 // for versioned api.
1545 /// @TODO We need a better global soluton
1546 $action_argv_id = 2;
1547 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1548 $action_argv_id = 3;
1551 if (DI::args()->getArgc() <= $action_argv_id) {
1552 throw new BadRequestException("Invalid request.");
1554 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1555 if (DI::args()->getArgc() == $action_argv_id + 2) {
1556 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1558 $itemid = intval($_REQUEST['id'] ?? 0);
1561 $item = Post::selectFirstForUser($uid, [], ['id' => $itemid, 'uid' => $uid]);
1563 if (!DBA::isResult($item)) {
1564 throw new BadRequestException("Invalid item.");
1569 $item['starred'] = 1;
1572 $item['starred'] = 0;
1575 throw new BadRequestException("Invalid action ".$action);
1578 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1581 throw new InternalServerErrorException("DB error");
1584 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1586 $ret = DI::twitterStatus()->createFromUriId($item['uri-id'], $item['uid'], $include_entities)->toArray();
1588 return DI::apiResponse()->formatData("status", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1591 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1592 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1595 * Returns all lists the user subscribes to.
1597 * @param string $type Return type (atom, rss, xml, json)
1599 * @return array|string
1600 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
1602 function api_lists_list($type)
1605 /// @TODO $ret is not filled here?
1606 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
1609 api_register_func('api/lists/list', 'api_lists_list', true);
1610 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
1613 * Returns all groups the user owns.
1615 * @param string $type Return type (atom, rss, xml, json)
1617 * @return array|string
1618 * @throws BadRequestException
1619 * @throws ForbiddenException
1620 * @throws ImagickException
1621 * @throws InternalServerErrorException
1622 * @throws UnauthorizedException
1623 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
1625 function api_lists_ownerships($type)
1627 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1628 $uid = BaseApi::getCurrentUserID();
1631 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1633 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
1635 // loop through all groups
1637 foreach ($groups as $group) {
1638 if ($group['visible']) {
1644 'name' => $group['name'],
1645 'id' => intval($group['id']),
1646 'id_str' => (string) $group['id'],
1647 'user' => $user_info,
1651 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
1654 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
1657 * Returns recent statuses from users in the specified group.
1659 * @param string $type Return type (atom, rss, xml, json)
1661 * @return array|string
1662 * @throws BadRequestException
1663 * @throws ForbiddenException
1664 * @throws ImagickException
1665 * @throws InternalServerErrorException
1666 * @throws UnauthorizedException
1667 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
1669 function api_lists_statuses($type)
1671 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1672 $uid = BaseApi::getCurrentUserID();
1674 if (empty($_REQUEST['list_id'])) {
1675 throw new BadRequestException('list_id not specified');
1679 $count = $_REQUEST['count'] ?? 20;
1680 $page = $_REQUEST['page'] ?? 1;
1681 $since_id = $_REQUEST['since_id'] ?? 0;
1682 $max_id = $_REQUEST['max_id'] ?? 0;
1683 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1684 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1686 $start = max(0, ($page - 1) * $count);
1688 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
1689 $gids = array_column($groups, 'contact-id');
1690 $condition = ['uid' => $uid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
1691 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
1694 $condition[0] .= " AND `id` <= ?";
1695 $condition[] = $max_id;
1697 if ($exclude_replies > 0) {
1698 $condition[0] .= ' AND `gravity` = ?';
1699 $condition[] = GRAVITY_PARENT;
1701 if ($conversation_id > 0) {
1702 $condition[0] .= " AND `parent` = ?";
1703 $condition[] = $conversation_id;
1706 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1707 $statuses = Post::selectForUser($uid, [], $condition, $params);
1709 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1712 while ($status = DBA::fetch($statuses)) {
1713 $items[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1715 DBA::close($statuses);
1717 return DI::apiResponse()->formatData("statuses", $type, ['status' => $items], Contact::getPublicIdByUserId($uid));
1720 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
1723 * Returns either the friends of the follower list
1725 * Considers friends and followers lists to be private and won't return
1726 * anything if any user_id parameter is passed.
1728 * @param string $qtype Either "friends" or "followers"
1729 * @return boolean|array
1730 * @throws BadRequestException
1731 * @throws ForbiddenException
1732 * @throws ImagickException
1733 * @throws InternalServerErrorException
1734 * @throws UnauthorizedException
1736 function api_statuses_f($qtype)
1738 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1739 $uid = BaseApi::getCurrentUserID();
1742 $count = $_GET['count'] ?? 20;
1743 $page = $_GET['page'] ?? 1;
1745 $start = max(0, ($page - 1) * $count);
1747 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
1748 /* this is to stop Hotot to load friends multiple times
1749 * I'm not sure if I'm missing return something or
1750 * is a bug in hotot. Workaround, meantime
1754 return array('$users' => $ret);*/
1759 if ($qtype == 'friends') {
1760 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
1761 } elseif ($qtype == 'followers') {
1762 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
1765 if ($qtype == 'blocks') {
1766 $sql_filter = 'AND `blocked` AND NOT `pending`';
1767 } elseif ($qtype == 'incoming') {
1768 $sql_filter = 'AND `pending`';
1770 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
1773 // @todo This query most likely can be replaced with a Contact::select...
1774 $r = DBA::toArray(DBA::p(
1789 foreach ($r as $cid) {
1790 $user = DI::twitterUser()->createFromContactId($cid['id'], $uid, false)->toArray();
1791 // "uid" is only needed for some internal stuff, so remove it from here
1792 unset($user['uid']);
1799 return ['user' => $ret];
1803 * Returns the list of friends of the provided user
1805 * @deprecated By Twitter API in favor of friends/list
1807 * @param string $type Either "json" or "xml"
1808 * @return boolean|string|array
1809 * @throws BadRequestException
1810 * @throws ForbiddenException
1812 function api_statuses_friends($type)
1814 $data = api_statuses_f("friends");
1815 if ($data === false) {
1818 return DI::apiResponse()->formatData("users", $type, $data);
1821 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
1824 * Returns the list of followers of the provided user
1826 * @deprecated By Twitter API in favor of friends/list
1828 * @param string $type Either "json" or "xml"
1829 * @return boolean|string|array
1830 * @throws BadRequestException
1831 * @throws ForbiddenException
1833 function api_statuses_followers($type)
1835 $data = api_statuses_f("followers");
1836 if ($data === false) {
1839 return DI::apiResponse()->formatData("users", $type, $data);
1842 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
1845 * Returns the list of blocked users
1847 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
1849 * @param string $type Either "json" or "xml"
1851 * @return boolean|string|array
1852 * @throws BadRequestException
1853 * @throws ForbiddenException
1855 function api_blocks_list($type)
1857 $data = api_statuses_f('blocks');
1858 if ($data === false) {
1861 return DI::apiResponse()->formatData("users", $type, $data);
1864 api_register_func('api/blocks/list', 'api_blocks_list', true);
1867 * Returns the list of pending users IDs
1869 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
1871 * @param string $type Either "json" or "xml"
1873 * @return boolean|string|array
1874 * @throws BadRequestException
1875 * @throws ForbiddenException
1877 function api_friendships_incoming($type)
1879 $data = api_statuses_f('incoming');
1880 if ($data === false) {
1885 foreach ($data['user'] as $user) {
1886 $ids[] = $user['id'];
1889 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
1892 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
1895 * Sends a new direct message.
1897 * @param string $type Return type (atom, rss, xml, json)
1899 * @return array|string
1900 * @throws BadRequestException
1901 * @throws ForbiddenException
1902 * @throws ImagickException
1903 * @throws InternalServerErrorException
1904 * @throws NotFoundException
1905 * @throws UnauthorizedException
1906 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
1908 function api_direct_messages_new($type)
1910 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1911 $uid = BaseApi::getCurrentUserID();
1913 if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
1917 $sender = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1919 $cid = BaseApi::getContactIDForSearchterm($_POST['screen_name'] ?? '', $_POST['user_id'] ?? 0, $uid);
1921 throw new NotFoundException('Recipient not found');
1925 if (!empty($_REQUEST['replyto'])) {
1926 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
1927 $replyto = $mail['parent-uri'];
1928 $sub = $mail['title'];
1930 if (!empty($_REQUEST['title'])) {
1931 $sub = $_REQUEST['title'];
1933 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
1937 $cdata = Contact::getPublicAndUserContactID($cid, $uid);
1939 $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
1942 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
1943 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid, true)->toArray(), $sender);
1945 $ret = ["error" => $id];
1948 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
1951 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
1954 * delete a direct_message from mail table through api
1956 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1957 * @return string|array
1958 * @throws BadRequestException
1959 * @throws ForbiddenException
1960 * @throws ImagickException
1961 * @throws InternalServerErrorException
1962 * @throws UnauthorizedException
1963 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
1965 function api_direct_messages_destroy($type)
1967 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1968 $uid = BaseApi::getCurrentUserID();
1971 $id = $_REQUEST['id'] ?? 0;
1973 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
1974 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
1975 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
1977 // error if no id or parenturi specified (for clients posting parent-uri as well)
1978 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
1979 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
1980 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
1983 // BadRequestException if no id specified (for clients using Twitter API)
1985 throw new BadRequestException('Message id not specified');
1988 // add parent-uri to sql command if specified by calling app
1989 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
1991 // error message if specified id is not in database
1992 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
1993 if ($verbose == "true") {
1994 $answer = ['result' => 'error', 'message' => 'message id not in database'];
1995 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
1997 /// @todo BadRequestException ok for Twitter API clients?
1998 throw new BadRequestException('message id not in database');
2002 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
2004 if ($verbose == "true") {
2007 $answer = ['result' => 'ok', 'message' => 'message deleted'];
2008 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
2010 $answer = ['result' => 'error', 'message' => 'unknown error'];
2011 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2014 /// @todo return JSON data like Twitter API not yet implemented
2017 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2022 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2023 * @return string|array
2024 * @throws HTTPException\BadRequestException
2025 * @throws HTTPException\ExpectationFailedException
2026 * @throws HTTPException\ForbiddenException
2027 * @throws HTTPException\InternalServerErrorException
2028 * @throws HTTPException\NotFoundException
2029 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
2031 function api_friendships_destroy($type)
2033 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2034 $uid = BaseApi::getCurrentUserID();
2036 $owner = User::getOwnerDataById($uid);
2038 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
2039 throw new HTTPException\NotFoundException('Error Processing Request');
2042 $contact_id = $_REQUEST['user_id'] ?? 0;
2044 if (empty($contact_id)) {
2045 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
2046 throw new HTTPException\BadRequestException('no user_id specified');
2049 // Get Contact by given id
2050 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
2052 if(!DBA::isResult($contact)) {
2053 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
2054 throw new HTTPException\NotFoundException('no contact found to given ID');
2057 $url = $contact['url'];
2059 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
2060 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
2061 Strings::normaliseLink($url), $url];
2062 $contact = DBA::selectFirst('contact', [], $condition);
2064 if (!DBA::isResult($contact)) {
2065 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
2066 throw new HTTPException\NotFoundException('Not following Contact');
2070 $result = Contact::terminateFriendship($owner, $contact);
2072 if ($result === null) {
2073 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
2074 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
2077 if ($result === false) {
2078 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
2080 } catch (Exception $e) {
2081 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
2082 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
2085 // "uid" is only needed for some internal stuff, so remove it from here
2086 unset($contact['uid']);
2088 // Set screen_name since Twidere requests it
2089 $contact['screen_name'] = $contact['nick'];
2091 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
2094 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
2098 * @param string $type Return type (atom, rss, xml, json)
2099 * @param string $box
2100 * @param string $verbose
2102 * @return array|string
2103 * @throws BadRequestException
2104 * @throws ForbiddenException
2105 * @throws ImagickException
2106 * @throws InternalServerErrorException
2107 * @throws UnauthorizedException
2109 function api_direct_messages_box($type, $box, $verbose)
2111 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2112 $uid = BaseApi::getCurrentUserID();
2115 $count = $_GET['count'] ?? 20;
2116 $page = $_REQUEST['page'] ?? 1;
2118 $since_id = $_REQUEST['since_id'] ?? 0;
2119 $max_id = $_REQUEST['max_id'] ?? 0;
2121 $user_id = $_REQUEST['user_id'] ?? '';
2122 $screen_name = $_REQUEST['screen_name'] ?? '';
2124 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2126 $profile_url = $user_info["url"];
2129 $start = max(0, ($page - 1) * $count);
2134 if ($box=="sentbox") {
2135 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
2136 } elseif ($box == "conversation") {
2137 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
2138 } elseif ($box == "all") {
2139 $sql_extra = "true";
2140 } elseif ($box == "inbox") {
2141 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
2145 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
2148 if ($user_id != "") {
2149 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2150 } elseif ($screen_name !="") {
2151 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
2154 $r = DBA::toArray(DBA::p(
2155 "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 ?,?",
2161 if ($verbose == "true" && !DBA::isResult($r)) {
2162 $answer = ['result' => 'error', 'message' => 'no mails available'];
2163 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
2167 foreach ($r as $item) {
2168 if ($box == "inbox" || $item['from-url'] != $profile_url) {
2169 $recipient = $user_info;
2170 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2171 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
2172 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2173 $sender = $user_info;
2176 if (isset($recipient) && isset($sender)) {
2177 $ret[] = api_format_messages($item, $recipient, $sender);
2181 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2185 * Returns the most recent direct messages sent by the user.
2187 * @param string $type Return type (atom, rss, xml, json)
2189 * @return array|string
2190 * @throws BadRequestException
2191 * @throws ForbiddenException
2192 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
2194 function api_direct_messages_sentbox($type)
2196 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2197 return api_direct_messages_box($type, "sentbox", $verbose);
2200 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
2203 * Returns the most recent direct messages sent to the user.
2205 * @param string $type Return type (atom, rss, xml, json)
2207 * @return array|string
2208 * @throws BadRequestException
2209 * @throws ForbiddenException
2210 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
2212 function api_direct_messages_inbox($type)
2214 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2215 return api_direct_messages_box($type, "inbox", $verbose);
2218 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
2222 * @param string $type Return type (atom, rss, xml, json)
2224 * @return array|string
2225 * @throws BadRequestException
2226 * @throws ForbiddenException
2228 function api_direct_messages_all($type)
2230 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2231 return api_direct_messages_box($type, "all", $verbose);
2234 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
2238 * @param string $type Return type (atom, rss, xml, json)
2240 * @return array|string
2241 * @throws BadRequestException
2242 * @throws ForbiddenException
2244 function api_direct_messages_conversation($type)
2246 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2247 return api_direct_messages_box($type, "conversation", $verbose);
2250 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
2253 * list all photos of the authenticated user
2255 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2256 * @return string|array
2257 * @throws ForbiddenException
2258 * @throws InternalServerErrorException
2260 function api_fr_photos_list($type)
2262 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2263 $uid = BaseApi::getCurrentUserID();
2265 $r = DBA::toArray(DBA::p(
2266 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
2267 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
2268 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
2269 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
2272 'image/jpeg' => 'jpg',
2273 'image/png' => 'png',
2274 'image/gif' => 'gif'
2276 $data = ['photo'=>[]];
2277 if (DBA::isResult($r)) {
2278 foreach ($r as $rr) {
2280 $photo['id'] = $rr['resource-id'];
2281 $photo['album'] = $rr['album'];
2282 $photo['filename'] = $rr['filename'];
2283 $photo['type'] = $rr['type'];
2284 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
2285 $photo['created'] = $rr['created'];
2286 $photo['edited'] = $rr['edited'];
2287 $photo['desc'] = $rr['desc'];
2289 if ($type == "xml") {
2290 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
2292 $photo['thumb'] = $thumb;
2293 $data['photo'][] = $photo;
2297 return DI::apiResponse()->formatData("photos", $type, $data);
2300 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2303 * upload a new photo or change an existing photo
2305 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2306 * @return string|array
2307 * @throws BadRequestException
2308 * @throws ForbiddenException
2309 * @throws ImagickException
2310 * @throws InternalServerErrorException
2311 * @throws NotFoundException
2313 function api_fr_photo_create_update($type)
2315 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2316 $uid = BaseApi::getCurrentUserID();
2319 $photo_id = $_REQUEST['photo_id'] ?? null;
2320 $desc = $_REQUEST['desc'] ?? null;
2321 $album = $_REQUEST['album'] ?? null;
2322 $album_new = $_REQUEST['album_new'] ?? null;
2323 $allow_cid = $_REQUEST['allow_cid'] ?? null;
2324 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
2325 $allow_gid = $_REQUEST['allow_gid'] ?? null;
2326 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
2327 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
2329 // do several checks on input parameters
2330 // we do not allow calls without album string
2331 if ($album == null) {
2332 throw new BadRequestException("no albumname specified");
2334 // if photo_id == null --> we are uploading a new photo
2335 if ($photo_id == null) {
2338 // error if no media posted in create-mode
2339 if (empty($_FILES['media'])) {
2341 throw new BadRequestException("no media data submitted");
2344 // album_new will be ignored in create-mode
2349 // check if photo is existing in databasei
2350 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
2351 throw new BadRequestException("photo not available");
2355 // checks on acl strings provided by clients
2356 $acl_input_error = false;
2357 $acl_input_error |= check_acl_input($allow_cid, $uid);
2358 $acl_input_error |= check_acl_input($deny_cid, $uid);
2359 $acl_input_error |= check_acl_input($allow_gid, $uid);
2360 $acl_input_error |= check_acl_input($deny_gid, $uid);
2361 if ($acl_input_error) {
2362 throw new BadRequestException("acl data invalid");
2364 // now let's upload the new media in create-mode
2365 if ($mode == "create") {
2366 $media = $_FILES['media'];
2367 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, Photo::DEFAULT, $visibility, null, $uid);
2369 // return success of updating or error message
2370 if (!is_null($data)) {
2371 return DI::apiResponse()->formatData("photo_create", $type, $data);
2373 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
2377 // now let's do the changes in update-mode
2378 if ($mode == "update") {
2379 $updated_fields = [];
2381 if (!is_null($desc)) {
2382 $updated_fields['desc'] = $desc;
2385 if (!is_null($album_new)) {
2386 $updated_fields['album'] = $album_new;
2389 if (!is_null($allow_cid)) {
2390 $allow_cid = trim($allow_cid);
2391 $updated_fields['allow_cid'] = $allow_cid;
2394 if (!is_null($deny_cid)) {
2395 $deny_cid = trim($deny_cid);
2396 $updated_fields['deny_cid'] = $deny_cid;
2399 if (!is_null($allow_gid)) {
2400 $allow_gid = trim($allow_gid);
2401 $updated_fields['allow_gid'] = $allow_gid;
2404 if (!is_null($deny_gid)) {
2405 $deny_gid = trim($deny_gid);
2406 $updated_fields['deny_gid'] = $deny_gid;
2410 if (count($updated_fields) > 0) {
2411 $nothingtodo = false;
2412 $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
2414 $nothingtodo = true;
2417 if (!empty($_FILES['media'])) {
2418 $nothingtodo = false;
2419 $media = $_FILES['media'];
2420 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
2421 if (!is_null($data)) {
2422 return DI::apiResponse()->formatData("photo_update", $type, $data);
2426 // return success of updating or error message
2428 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
2429 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
2432 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
2433 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
2435 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
2438 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
2441 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
2442 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
2445 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
2447 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2448 * @return string|array
2449 * @throws BadRequestException
2450 * @throws ForbiddenException
2451 * @throws InternalServerErrorException
2452 * @throws NotFoundException
2454 function api_fr_photo_detail($type)
2456 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2457 $uid = BaseApi::getCurrentUserID();
2459 if (empty($_REQUEST['photo_id'])) {
2460 throw new BadRequestException("No photo id.");
2463 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
2464 $photo_id = $_REQUEST['photo_id'];
2466 // prepare json/xml output with data from database for the requested photo
2467 $data = prepare_photo_data($type, $scale, $photo_id, $uid);
2469 return DI::apiResponse()->formatData("photo_detail", $type, $data);
2472 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2475 * updates the profile image for the user (either a specified profile or the default profile)
2477 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2479 * @return string|array
2480 * @throws BadRequestException
2481 * @throws ForbiddenException
2482 * @throws ImagickException
2483 * @throws InternalServerErrorException
2484 * @throws NotFoundException
2485 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
2487 function api_account_update_profile_image($type)
2489 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2490 $uid = BaseApi::getCurrentUserID();
2493 $profile_id = $_REQUEST['profile_id'] ?? 0;
2495 // error if image data is missing
2496 if (empty($_FILES['image'])) {
2497 throw new BadRequestException("no media data submitted");
2500 // check if specified profile id is valid
2501 if ($profile_id != 0) {
2502 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
2503 // error message if specified profile id is not in database
2504 if (!DBA::isResult($profile)) {
2505 throw new BadRequestException("profile_id not available");
2507 $is_default_profile = $profile['is-default'];
2509 $is_default_profile = 1;
2512 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
2514 if (!empty($_FILES['image'])) {
2515 $media = $_FILES['image'];
2516 } elseif (!empty($_FILES['media'])) {
2517 $media = $_FILES['media'];
2519 // save new profile image
2520 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
2523 if (is_array($media['type'])) {
2524 $filetype = $media['type'][0];
2526 $filetype = $media['type'];
2528 if ($filetype == "image/jpeg") {
2530 } elseif ($filetype == "image/png") {
2533 throw new InternalServerErrorException('Unsupported filetype');
2536 // change specified profile or all profiles to the new resource-id
2537 if ($is_default_profile) {
2538 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
2539 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
2541 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
2542 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
2543 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
2546 Contact::updateSelfFromUserID($uid, true);
2548 // Update global directory in background
2549 Profile::publishUpdate($uid);
2551 // output for client
2553 $skip_status = $_REQUEST['skip_status'] ?? false;
2555 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
2557 // "verified" isn't used here in the standard
2558 unset($user_info["verified"]);
2560 // "uid" is only needed for some internal stuff, so remove it from here
2561 unset($user_info['uid']);
2563 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
2565 // SaveMediaToDatabase failed for some reason
2566 throw new InternalServerErrorException("image upload failed");
2570 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
2573 * Return all or a specified group of the user with the containing contacts.
2575 * @param string $type Return type (atom, rss, xml, json)
2577 * @return array|string
2578 * @throws BadRequestException
2579 * @throws ForbiddenException
2580 * @throws ImagickException
2581 * @throws InternalServerErrorException
2582 * @throws UnauthorizedException
2584 function api_friendica_group_show($type)
2586 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2587 $uid = BaseApi::getCurrentUserID();
2590 $gid = $_REQUEST['gid'] ?? 0;
2592 // get data of the specified group id or all groups if not specified
2594 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
2596 // error message if specified gid is not in database
2597 if (!DBA::isResult($groups)) {
2598 throw new BadRequestException("gid not available");
2601 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
2604 // loop through all groups and retrieve all members for adding data in the user array
2606 foreach ($groups as $rr) {
2607 $members = Contact\Group::getById($rr['id']);
2610 if ($type == "xml") {
2611 $user_element = "users";
2613 foreach ($members as $member) {
2614 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
2615 $users[$k++.":user"] = $user;
2618 $user_element = "user";
2619 foreach ($members as $member) {
2620 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
2624 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
2626 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
2629 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
2634 * @param string $type Return type (atom, rss, xml, json)
2636 * @return array|string
2637 * @throws BadRequestException
2638 * @throws ForbiddenException
2639 * @throws ImagickException
2640 * @throws InternalServerErrorException
2641 * @throws UnauthorizedException
2642 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
2644 function api_lists_destroy($type)
2646 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2647 $uid = BaseApi::getCurrentUserID();
2650 $gid = $_REQUEST['list_id'] ?? 0;
2652 // error if no gid specified
2654 throw new BadRequestException('gid not specified');
2657 // get data of the specified group id
2658 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
2659 // error message if specified gid is not in database
2661 throw new BadRequestException('gid not available');
2664 if (Group::remove($gid)) {
2666 'name' => $group['name'],
2667 'id' => intval($gid),
2668 'id_str' => (string) $gid,
2669 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
2672 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
2676 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
2679 * Create the specified group with the posted array of contacts.
2681 * @param string $type Return type (atom, rss, xml, json)
2683 * @return array|string
2684 * @throws BadRequestException
2685 * @throws ForbiddenException
2686 * @throws ImagickException
2687 * @throws InternalServerErrorException
2688 * @throws UnauthorizedException
2690 function api_friendica_group_create($type)
2692 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2693 $uid = BaseApi::getCurrentUserID();
2696 $name = $_REQUEST['name'] ?? '';
2697 $json = json_decode($_POST['json'], true);
2698 $users = $json['user'];
2700 $success = group_create($name, $uid, $users);
2702 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
2705 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
2708 * Create a new group.
2710 * @param string $type Return type (atom, rss, xml, json)
2712 * @return array|string
2713 * @throws BadRequestException
2714 * @throws ForbiddenException
2715 * @throws ImagickException
2716 * @throws InternalServerErrorException
2717 * @throws UnauthorizedException
2718 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
2720 function api_lists_create($type)
2722 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2723 $uid = BaseApi::getCurrentUserID();
2726 $name = $_REQUEST['name'] ?? '';
2728 $success = group_create($name, $uid);
2729 if ($success['success']) {
2731 'name' => $success['name'],
2732 'id' => intval($success['gid']),
2733 'id_str' => (string) $success['gid'],
2734 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
2737 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
2741 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
2744 * Update the specified group with the posted array of contacts.
2746 * @param string $type Return type (atom, rss, xml, json)
2748 * @return array|string
2749 * @throws BadRequestException
2750 * @throws ForbiddenException
2751 * @throws ImagickException
2752 * @throws InternalServerErrorException
2753 * @throws UnauthorizedException
2755 function api_friendica_group_update($type)
2757 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2758 $uid = BaseApi::getCurrentUserID();
2761 $gid = $_REQUEST['gid'] ?? 0;
2762 $name = $_REQUEST['name'] ?? '';
2763 $json = json_decode($_POST['json'], true);
2764 $users = $json['user'];
2766 // error if no name specified
2768 throw new BadRequestException('group name not specified');
2771 // error if no gid specified
2773 throw new BadRequestException('gid not specified');
2777 $members = Contact\Group::getById($gid);
2778 foreach ($members as $member) {
2779 $cid = $member['id'];
2780 foreach ($users as $user) {
2781 $found = ($user['cid'] == $cid ? true : false);
2783 if (!isset($found) || !$found) {
2784 $gid = Group::getIdByName($uid, $name);
2785 Group::removeMember($gid, $cid);
2790 $erroraddinguser = false;
2792 foreach ($users as $user) {
2793 $cid = $user['cid'];
2795 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
2796 Group::addMember($gid, $cid);
2798 $erroraddinguser = true;
2799 $errorusers[] = $cid;
2803 // return success message incl. missing users in array
2804 $status = ($erroraddinguser ? "missing user" : "ok");
2805 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
2806 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
2809 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
2812 * Update information about a group.
2814 * @param string $type Return type (atom, rss, xml, json)
2816 * @return array|string
2817 * @throws BadRequestException
2818 * @throws ForbiddenException
2819 * @throws ImagickException
2820 * @throws InternalServerErrorException
2821 * @throws UnauthorizedException
2822 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
2824 function api_lists_update($type)
2826 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2827 $uid = BaseApi::getCurrentUserID();
2830 $gid = $_REQUEST['list_id'] ?? 0;
2831 $name = $_REQUEST['name'] ?? '';
2833 // error if no gid specified
2835 throw new BadRequestException('gid not specified');
2838 // get data of the specified group id
2839 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
2840 // error message if specified gid is not in database
2842 throw new BadRequestException('gid not available');
2845 if (Group::update($gid, $name)) {
2848 'id' => intval($gid),
2849 'id_str' => (string) $gid,
2850 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
2853 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
2857 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
2860 * search for direct_messages containing a searchstring through api
2862 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2863 * @param string $box
2864 * @return string|array (success: success=true if found and search_result contains found messages,
2865 * success=false if nothing was found, search_result='nothing found',
2866 * error: result=error with error message)
2867 * @throws BadRequestException
2868 * @throws ForbiddenException
2869 * @throws ImagickException
2870 * @throws InternalServerErrorException
2871 * @throws UnauthorizedException
2873 function api_friendica_direct_messages_search($type, $box = "")
2875 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2876 $uid = BaseApi::getCurrentUserID();
2879 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2880 $searchstring = $_REQUEST['searchstring'] ?? '';
2882 // error if no searchstring specified
2883 if ($searchstring == "") {
2884 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
2885 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
2888 // get data for the specified searchstring
2889 $r = DBA::toArray(DBA::p(
2890 "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",
2892 '%'.$searchstring.'%'
2895 $profile_url = $user_info["url"];
2897 // message if nothing was found
2898 if (!DBA::isResult($r)) {
2899 $success = ['success' => false, 'search_results' => 'problem with query'];
2900 } elseif (count($r) == 0) {
2901 $success = ['success' => false, 'search_results' => 'nothing found'];
2904 foreach ($r as $item) {
2905 if ($box == "inbox" || $item['from-url'] != $profile_url) {
2906 $recipient = $user_info;
2907 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2908 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
2909 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2910 $sender = $user_info;
2913 if (isset($recipient) && isset($sender)) {
2914 $ret[] = api_format_messages($item, $recipient, $sender);
2917 $success = ['success' => true, 'search_results' => $ret];
2920 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
2923 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);