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 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
692 * returns a 401 status code and an error message if not.
694 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
696 * @param string $type Return type (atom, rss, xml, json)
697 * @return array|string
698 * @throws BadRequestException
699 * @throws ForbiddenException
700 * @throws ImagickException
701 * @throws InternalServerErrorException
702 * @throws UnauthorizedException
704 function api_account_verify_credentials($type)
706 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
707 $uid = BaseApi::getCurrentUserID();
709 unset($_REQUEST['user_id']);
710 unset($_GET['user_id']);
712 unset($_REQUEST['screen_name']);
713 unset($_GET['screen_name']);
715 $skip_status = $_REQUEST['skip_status'] ?? false;
717 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
719 // "verified" isn't used here in the standard
720 unset($user_info["verified"]);
722 // "uid" is only needed for some internal stuff, so remove it from here
723 unset($user_info['uid']);
725 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
728 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
731 * Deprecated function to upload media.
733 * @param string $type Return type (atom, rss, xml, json)
735 * @return array|string
736 * @throws BadRequestException
737 * @throws ForbiddenException
738 * @throws ImagickException
739 * @throws InternalServerErrorException
740 * @throws UnauthorizedException
742 function api_statuses_mediap($type)
744 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
745 $uid = BaseApi::getCurrentUserID();
749 $_REQUEST['profile_uid'] = $uid;
750 $_REQUEST['api_source'] = true;
751 $txt = $_REQUEST['status'] ?? '';
753 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
754 $txt = HTML::toBBCodeVideo($txt);
755 $config = HTMLPurifier_Config::createDefault();
756 $config->set('Cache.DefinitionImpl', null);
757 $purifier = new HTMLPurifier($config);
758 $txt = $purifier->purify($txt);
760 $txt = HTML::toBBCode($txt);
762 $picture = wall_upload_post($a, false);
764 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
765 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
766 $item_id = item_post($a);
768 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
770 // output the post that we just posted.
771 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
772 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
775 /// @TODO move this to top of file or somewhere better!
776 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
779 * Updates the user’s current status.
781 * @param string $type Return type (atom, rss, xml, json)
783 * @return array|string
784 * @throws BadRequestException
785 * @throws ForbiddenException
786 * @throws ImagickException
787 * @throws InternalServerErrorException
788 * @throws TooManyRequestsException
789 * @throws UnauthorizedException
790 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
792 function api_statuses_update($type)
794 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
795 $uid = BaseApi::getCurrentUserID();
799 // convert $_POST array items to the form we use for web posts.
800 if (!empty($_REQUEST['htmlstatus'])) {
801 $txt = $_REQUEST['htmlstatus'];
802 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
803 $txt = HTML::toBBCodeVideo($txt);
805 $config = HTMLPurifier_Config::createDefault();
806 $config->set('Cache.DefinitionImpl', null);
808 $purifier = new HTMLPurifier($config);
809 $txt = $purifier->purify($txt);
811 $_REQUEST['body'] = HTML::toBBCode($txt);
814 $_REQUEST['body'] = $_REQUEST['status'] ?? null;
817 $_REQUEST['title'] = $_REQUEST['title'] ?? null;
819 $parent = $_REQUEST['in_reply_to_status_id'] ?? null;
821 // Twidere sends "-1" if it is no reply ...
826 if (ctype_digit($parent)) {
827 $_REQUEST['parent'] = $parent;
829 $_REQUEST['parent_uri'] = $parent;
832 if (!empty($_REQUEST['lat']) && !empty($_REQUEST['long'])) {
833 $_REQUEST['coord'] = sprintf("%s %s", $_REQUEST['lat'], $_REQUEST['long']);
835 $_REQUEST['profile_uid'] = $uid;
838 // Check for throttling (maximum posts per day, week and month)
839 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
840 if ($throttle_day > 0) {
841 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
843 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
844 $posts_day = Post::count($condition);
846 if ($posts_day > $throttle_day) {
847 logger::info('Daily posting limit reached for user ' . $uid);
848 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
849 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));
853 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
854 if ($throttle_week > 0) {
855 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
857 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
858 $posts_week = Post::count($condition);
860 if ($posts_week > $throttle_week) {
861 logger::info('Weekly posting limit reached for user ' . $uid);
862 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
863 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));
867 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
868 if ($throttle_month > 0) {
869 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
871 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
872 $posts_month = Post::count($condition);
874 if ($posts_month > $throttle_month) {
875 logger::info('Monthly posting limit reached for user ' . $uid);
876 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
877 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));
882 if (!empty($_REQUEST['media_ids'])) {
883 $ids = explode(',', $_REQUEST['media_ids']);
884 } elseif (!empty($_FILES['media'])) {
885 // upload the image if we have one
886 $picture = wall_upload_post($a, false);
887 if (is_array($picture)) {
888 $ids[] = $picture['id'];
896 foreach ($ids as $id) {
897 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
898 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
899 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
900 ORDER BY `photo`.`width` DESC LIMIT 2", $id, $uid));
902 if (!empty($media)) {
903 $ressources[] = $media[0]['resource-id'];
904 $phototypes = Images::supportedTypes();
905 $ext = $phototypes[$media[0]['type']];
907 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
908 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
909 'size' => $media[0]['datasize'],
910 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
911 'description' => $media[0]['desc'] ?? '',
912 'width' => $media[0]['width'],
913 'height' => $media[0]['height']];
915 if (count($media) > 1) {
916 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
917 $attachment['preview-width'] = $media[1]['width'];
918 $attachment['preview-height'] = $media[1]['height'];
920 $attachments[] = $attachment;
924 // We have to avoid that the post is rejected because of an empty body
925 if (empty($_REQUEST['body'])) {
926 $_REQUEST['body'] = '[hr]';
930 if (!empty($attachments)) {
931 $_REQUEST['attachments'] = $attachments;
934 // set this so that the item_post() function is quiet and doesn't redirect or emit json
936 $_REQUEST['api_source'] = true;
938 if (empty($_REQUEST['source'])) {
939 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
942 // call out normal post function
943 $item_id = item_post($a);
945 if (!empty($ressources) && !empty($item_id)) {
946 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
947 foreach ($ressources as $ressource) {
948 Photo::setPermissionForRessource($ressource, $uid, $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
952 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
954 // output the post that we just posted.
955 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
956 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
959 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
960 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
963 * Uploads an image to Friendica.
966 * @throws BadRequestException
967 * @throws ForbiddenException
968 * @throws ImagickException
969 * @throws InternalServerErrorException
970 * @throws UnauthorizedException
971 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
973 function api_media_upload()
975 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
977 if (empty($_FILES['media'])) {
979 throw new BadRequestException("No media.");
982 $media = wall_upload_post(DI::app(), false);
985 throw new InternalServerErrorException();
989 $returndata["media_id"] = $media["id"];
990 $returndata["media_id_string"] = (string)$media["id"];
991 $returndata["size"] = $media["size"];
992 $returndata["image"] = ["w" => $media["width"],
993 "h" => $media["height"],
994 "image_type" => $media["type"],
995 "friendica_preview_url" => $media["preview"]];
997 Logger::info('Media uploaded', ['return' => $returndata]);
999 return ["media" => $returndata];
1002 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1005 * Updates media meta data (picture descriptions)
1007 * @param string $type Return type (atom, rss, xml, json)
1009 * @return array|string
1010 * @throws BadRequestException
1011 * @throws ForbiddenException
1012 * @throws ImagickException
1013 * @throws InternalServerErrorException
1014 * @throws TooManyRequestsException
1015 * @throws UnauthorizedException
1016 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1018 * @todo Compare the corresponding Twitter function for correct return values
1020 function api_media_metadata_create($type)
1022 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1023 $uid = BaseApi::getCurrentUserID();
1025 $postdata = Network::postdata();
1027 if (empty($postdata)) {
1028 throw new BadRequestException("No post data");
1031 $data = json_decode($postdata, true);
1033 throw new BadRequestException("Invalid post data");
1036 if (empty($data['media_id']) || empty($data['alt_text'])) {
1037 throw new BadRequestException("Missing post data values");
1040 if (empty($data['alt_text']['text'])) {
1041 throw new BadRequestException("No alt text.");
1044 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1046 $condition = ['id' => $data['media_id'], 'uid' => $uid];
1047 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1048 if (!DBA::isResult($photo)) {
1049 throw new BadRequestException("Metadata not found.");
1052 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1055 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1058 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1059 * The author's most recent status will be returned inline.
1061 * @param string $type Return type (atom, rss, xml, json)
1062 * @return array|string
1063 * @throws BadRequestException
1064 * @throws ImagickException
1065 * @throws InternalServerErrorException
1066 * @throws UnauthorizedException
1067 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1069 function api_users_show($type)
1071 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1072 $uid = BaseApi::getCurrentUserID();
1074 $user_info = DI::twitterUser()->createFromUserId($uid, false)->toArray();
1076 // "uid" is only needed for some internal stuff, so remove it from here
1077 unset($user_info['uid']);
1079 return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
1082 api_register_func('api/users/show', 'api_users_show');
1083 api_register_func('api/externalprofile/show', 'api_users_show');
1086 * Search a public user account.
1088 * @param string $type Return type (atom, rss, xml, json)
1090 * @return array|string
1091 * @throws BadRequestException
1092 * @throws ImagickException
1093 * @throws InternalServerErrorException
1094 * @throws UnauthorizedException
1095 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1097 function api_users_search($type)
1099 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1100 $uid = BaseApi::getCurrentUserID();
1104 if (!empty($_GET['q'])) {
1105 $contacts = Contact::selectToArray(
1108 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1116 if (DBA::isResult($contacts)) {
1118 foreach ($contacts as $contact) {
1119 $user_info = DI::twitterUser()->createFromContactId($contact['id'], $uid, false)->toArray();
1121 if ($type == 'xml') {
1122 $userlist[$k++ . ':user'] = $user_info;
1124 $userlist[] = $user_info;
1127 $userlist = ['users' => $userlist];
1129 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1132 throw new BadRequestException('No search term specified.');
1135 return DI::apiResponse()->formatData('users', $type, $userlist);
1138 api_register_func('api/users/search', 'api_users_search');
1141 * Return user objects
1143 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1145 * @param string $type Return format: json or xml
1147 * @return array|string
1148 * @throws BadRequestException
1149 * @throws ImagickException
1150 * @throws InternalServerErrorException
1151 * @throws NotFoundException if the results are empty.
1152 * @throws UnauthorizedException
1154 function api_users_lookup($type)
1156 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1157 $uid = BaseApi::getCurrentUserID();
1161 if (!empty($_REQUEST['user_id'])) {
1162 foreach (explode(',', $_REQUEST['user_id']) as $cid) {
1163 if (!empty($cid) && is_numeric($cid)) {
1164 $users[] = DI::twitterUser()->createFromContactId((int)$cid, $uid, false)->toArray();
1169 if (empty($users)) {
1170 throw new NotFoundException;
1173 return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
1176 api_register_func('api/users/lookup', 'api_users_lookup', true);
1179 * Returns statuses that match a specified query.
1181 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1183 * @param string $type Return format: json, xml, atom, rss
1185 * @return array|string
1186 * @throws BadRequestException if the "q" parameter is missing.
1187 * @throws ForbiddenException
1188 * @throws ImagickException
1189 * @throws InternalServerErrorException
1190 * @throws UnauthorizedException
1192 function api_search($type)
1194 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1195 $uid = BaseApi::getCurrentUserID();
1197 if (empty($_REQUEST['q'])) {
1198 throw new BadRequestException('q parameter is required.');
1201 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1204 $data['status'] = [];
1206 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1207 if (!empty($_REQUEST['rpp'])) {
1208 $count = $_REQUEST['rpp'];
1209 } elseif (!empty($_REQUEST['count'])) {
1210 $count = $_REQUEST['count'];
1213 $since_id = $_REQUEST['since_id'] ?? 0;
1214 $max_id = $_REQUEST['max_id'] ?? 0;
1215 $page = $_REQUEST['page'] ?? 1;
1217 $start = max(0, ($page - 1) * $count);
1219 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1220 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1221 $searchTerm = $matches[1];
1222 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, $uid];
1223 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1225 while ($tag = DBA::fetch($tags)) {
1226 $uriids[] = $tag['uri-id'];
1230 if (empty($uriids)) {
1231 return DI::apiResponse()->formatData('statuses', $type, $data);
1234 $condition = ['uri-id' => $uriids];
1235 if ($exclude_replies) {
1236 $condition['gravity'] = GRAVITY_PARENT;
1239 $params['group_by'] = ['uri-id'];
1241 $condition = ["`id` > ?
1242 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1243 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1244 AND `body` LIKE CONCAT('%',?,'%')",
1245 $since_id, $uid, $_REQUEST['q']];
1247 $condition[0] .= ' AND `id` <= ?';
1248 $condition[] = $max_id;
1254 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1255 $id = Item::fetchByLink($searchTerm, $uid);
1258 $id = Item::fetchByLink($searchTerm);
1262 $statuses = Post::select([], ['id' => $id]);
1266 $statuses = $statuses ?: Post::selectForUser($uid, [], $condition, $params);
1268 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1271 while ($status = DBA::fetch($statuses)) {
1272 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1274 DBA::close($statuses);
1276 $data['status'] = $ret;
1278 return DI::apiResponse()->formatData('statuses', $type, $data);
1281 api_register_func('api/search/tweets', 'api_search', true);
1282 api_register_func('api/search', 'api_search', true);
1285 * Returns the most recent statuses posted by the user and the users they follow.
1287 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1289 * @param string $type Return type (atom, rss, xml, json)
1291 * @return array|string
1292 * @throws BadRequestException
1293 * @throws ForbiddenException
1294 * @throws ImagickException
1295 * @throws InternalServerErrorException
1296 * @throws UnauthorizedException
1297 * @todo Optional parameters
1298 * @todo Add reply info
1300 function api_statuses_home_timeline($type)
1302 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1303 $uid = BaseApi::getCurrentUserID();
1305 unset($_REQUEST['user_id']);
1306 unset($_GET['user_id']);
1308 unset($_REQUEST['screen_name']);
1309 unset($_GET['screen_name']);
1311 // get last network messages
1314 $count = $_REQUEST['count'] ?? 20;
1315 $page = $_REQUEST['page']?? 0;
1316 $since_id = $_REQUEST['since_id'] ?? 0;
1317 $max_id = $_REQUEST['max_id'] ?? 0;
1318 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1319 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1321 $start = max(0, ($page - 1) * $count);
1323 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1324 $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1327 $condition[0] .= " AND `id` <= ?";
1328 $condition[] = $max_id;
1330 if ($exclude_replies) {
1331 $condition[0] .= ' AND `gravity` = ?';
1332 $condition[] = GRAVITY_PARENT;
1334 if ($conversation_id > 0) {
1335 $condition[0] .= " AND `parent` = ?";
1336 $condition[] = $conversation_id;
1339 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1340 $statuses = Post::selectForUser($uid, [], $condition, $params);
1342 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1346 while ($status = DBA::fetch($statuses)) {
1347 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1348 $idarray[] = intval($status['id']);
1350 DBA::close($statuses);
1352 if (!empty($idarray)) {
1353 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1355 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1359 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1363 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1364 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1367 * Returns the most recent statuses from public users.
1369 * @param string $type Return type (atom, rss, xml, json)
1371 * @return array|string
1372 * @throws BadRequestException
1373 * @throws ForbiddenException
1374 * @throws ImagickException
1375 * @throws InternalServerErrorException
1376 * @throws UnauthorizedException
1378 function api_statuses_public_timeline($type)
1380 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1381 $uid = BaseApi::getCurrentUserID();
1383 // get last network messages
1386 $count = $_REQUEST['count'] ?? 20;
1387 $page = $_REQUEST['page'] ?? 1;
1388 $since_id = $_REQUEST['since_id'] ?? 0;
1389 $max_id = $_REQUEST['max_id'] ?? 0;
1390 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1391 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1393 $start = max(0, ($page - 1) * $count);
1395 if ($exclude_replies && !$conversation_id) {
1396 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1397 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1400 $condition[0] .= " AND `id` <= ?";
1401 $condition[] = $max_id;
1404 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1405 $statuses = Post::selectForUser($uid, [], $condition, $params);
1407 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1408 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1411 $condition[0] .= " AND `id` <= ?";
1412 $condition[] = $max_id;
1414 if ($conversation_id > 0) {
1415 $condition[0] .= " AND `parent` = ?";
1416 $condition[] = $conversation_id;
1419 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1420 $statuses = Post::selectForUser($uid, [], $condition, $params);
1423 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1426 while ($status = DBA::fetch($statuses)) {
1427 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1429 DBA::close($statuses);
1431 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1434 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1437 * Returns the most recent statuses posted by users this node knows about.
1439 * @param string $type Return format: json, xml, atom, rss
1440 * @return array|string
1441 * @throws BadRequestException
1442 * @throws ForbiddenException
1443 * @throws ImagickException
1444 * @throws InternalServerErrorException
1445 * @throws UnauthorizedException
1447 function api_statuses_networkpublic_timeline($type)
1449 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1450 $uid = BaseApi::getCurrentUserID();
1452 $since_id = $_REQUEST['since_id'] ?? 0;
1453 $max_id = $_REQUEST['max_id'] ?? 0;
1456 $count = $_REQUEST['count'] ?? 20;
1457 $page = $_REQUEST['page'] ?? 1;
1459 $start = max(0, ($page - 1) * $count);
1461 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1462 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1465 $condition[0] .= " AND `id` <= ?";
1466 $condition[] = $max_id;
1469 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1470 $statuses = Post::selectForUser($uid, Item::DISPLAY_FIELDLIST, $condition, $params);
1472 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1475 while ($status = DBA::fetch($statuses)) {
1476 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1478 DBA::close($statuses);
1480 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1483 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1486 * Returns a single status.
1488 * @param string $type Return type (atom, rss, xml, json)
1490 * @return array|string
1491 * @throws BadRequestException
1492 * @throws ForbiddenException
1493 * @throws ImagickException
1494 * @throws InternalServerErrorException
1495 * @throws UnauthorizedException
1496 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1498 function api_statuses_show($type)
1500 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1501 $uid = BaseApi::getCurrentUserID();
1504 $id = intval(DI::args()->getArgv()[3] ?? 0);
1507 $id = intval($_REQUEST['id'] ?? 0);
1512 $id = intval(DI::args()->getArgv()[4] ?? 0);
1515 logger::notice('API: api_statuses_show: ' . $id);
1517 $conversation = !empty($_REQUEST['conversation']);
1519 // try to fetch the item for the local user - or the public item, if there is no local one
1520 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1521 if (!DBA::isResult($uri_item)) {
1522 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1525 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1526 if (!DBA::isResult($item)) {
1527 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1532 if ($conversation) {
1533 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1534 $params = ['order' => ['id' => true]];
1536 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1540 $statuses = Post::selectForUser($uid, [], $condition, $params);
1542 /// @TODO How about copying this to above methods which don't check $r ?
1543 if (!DBA::isResult($statuses)) {
1544 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1547 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1550 while ($status = DBA::fetch($statuses)) {
1551 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1553 DBA::close($statuses);
1555 if ($conversation) {
1556 $data = ['status' => $ret];
1557 return DI::apiResponse()->formatData("statuses", $type, $data);
1559 $data = ['status' => $ret[0]];
1560 return DI::apiResponse()->formatData("status", $type, $data);
1564 api_register_func('api/statuses/show', 'api_statuses_show', true);
1568 * @param string $type Return type (atom, rss, xml, json)
1570 * @return array|string
1571 * @throws BadRequestException
1572 * @throws ForbiddenException
1573 * @throws ImagickException
1574 * @throws InternalServerErrorException
1575 * @throws UnauthorizedException
1576 * @todo nothing to say?
1578 function api_conversation_show($type)
1580 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1581 $uid = BaseApi::getCurrentUserID();
1584 $id = intval(DI::args()->getArgv()[3] ?? 0);
1585 $since_id = intval($_REQUEST['since_id'] ?? 0);
1586 $max_id = intval($_REQUEST['max_id'] ?? 0);
1587 $count = intval($_REQUEST['count'] ?? 20);
1588 $page = intval($_REQUEST['page'] ?? 1);
1590 $start = max(0, ($page - 1) * $count);
1593 $id = intval($_REQUEST['id'] ?? 0);
1598 $id = intval(DI::args()->getArgv()[4] ?? 0);
1601 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1603 // try to fetch the item for the local user - or the public item, if there is no local one
1604 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1605 if (!DBA::isResult($item)) {
1606 throw new BadRequestException("There is no status with the id $id.");
1609 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1610 if (!DBA::isResult($parent)) {
1611 throw new BadRequestException("There is no status with this id.");
1614 $id = $parent['id'];
1616 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1617 $id, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1620 $condition[0] .= " AND `id` <= ?";
1621 $condition[] = $max_id;
1624 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1625 $statuses = Post::selectForUser($uid, [], $condition, $params);
1627 if (!DBA::isResult($statuses)) {
1628 throw new BadRequestException("There is no status with id $id.");
1631 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1634 while ($status = DBA::fetch($statuses)) {
1635 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1637 DBA::close($statuses);
1639 $data = ['status' => $ret];
1640 return DI::apiResponse()->formatData("statuses", $type, $data);
1643 api_register_func('api/conversation/show', 'api_conversation_show', true);
1644 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1649 * @param string $type Return type (atom, rss, xml, json)
1651 * @return array|string
1652 * @throws BadRequestException
1653 * @throws ForbiddenException
1654 * @throws ImagickException
1655 * @throws InternalServerErrorException
1656 * @throws UnauthorizedException
1657 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1659 function api_statuses_repeat($type)
1661 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1662 $uid = BaseApi::getCurrentUserID();
1665 $id = intval(DI::args()->getArgv()[3] ?? 0);
1668 $id = intval($_REQUEST['id'] ?? 0);
1673 $id = intval(DI::args()->getArgv()[4] ?? 0);
1676 logger::notice('API: api_statuses_repeat: ' . $id);
1678 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1679 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1681 if (DBA::isResult($item) && !empty($item['body'])) {
1682 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1683 if (!Item::performActivity($id, 'announce', $uid)) {
1684 throw new InternalServerErrorException();
1689 if (strpos($item['body'], "[/share]") !== false) {
1690 $pos = strpos($item['body'], "[share");
1691 $post = substr($item['body'], $pos);
1693 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1695 if (!empty($item['title'])) {
1696 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1699 $post .= $item['body'];
1700 $post .= "[/share]";
1702 $_REQUEST['body'] = $post;
1703 $_REQUEST['profile_uid'] = $uid;
1704 $_REQUEST['api_source'] = true;
1706 if (empty($_REQUEST['source'])) {
1707 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
1710 $item_id = item_post(DI::app());
1713 throw new ForbiddenException();
1716 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1718 // output the post that we just posted.
1719 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
1720 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
1723 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1726 * Destroys a specific status.
1728 * @param string $type Return type (atom, rss, xml, json)
1730 * @return array|string
1731 * @throws BadRequestException
1732 * @throws ForbiddenException
1733 * @throws ImagickException
1734 * @throws InternalServerErrorException
1735 * @throws UnauthorizedException
1736 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1738 function api_statuses_destroy($type)
1740 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1741 $uid = BaseApi::getCurrentUserID();
1744 $id = intval(DI::args()->getArgv()[3] ?? 0);
1747 $id = intval($_REQUEST['id'] ?? 0);
1752 $id = intval(DI::args()->getArgv()[4] ?? 0);
1755 logger::notice('API: api_statuses_destroy: ' . $id);
1757 $ret = api_statuses_show($type);
1759 Item::deleteForUser(['id' => $id], $uid);
1764 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1767 * Returns the most recent mentions.
1769 * @param string $type Return type (atom, rss, xml, json)
1771 * @return array|string
1772 * @throws BadRequestException
1773 * @throws ForbiddenException
1774 * @throws ImagickException
1775 * @throws InternalServerErrorException
1776 * @throws UnauthorizedException
1777 * @see http://developer.twitter.com/doc/get/statuses/mentions
1779 function api_statuses_mentions($type)
1781 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1782 $uid = BaseApi::getCurrentUserID();
1784 unset($_REQUEST['user_id']);
1785 unset($_GET['user_id']);
1787 unset($_REQUEST['screen_name']);
1788 unset($_GET['screen_name']);
1790 // get last network messages
1793 $since_id = intval($_REQUEST['since_id'] ?? 0);
1794 $max_id = intval($_REQUEST['max_id'] ?? 0);
1795 $count = intval($_REQUEST['count'] ?? 20);
1796 $page = intval($_REQUEST['page'] ?? 1);
1798 $start = max(0, ($page - 1) * $count);
1800 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1801 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1802 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1805 GRAVITY_PARENT, GRAVITY_COMMENT,
1807 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1808 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1809 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1814 $query .= " AND `id` <= ?";
1815 $condition[] = $max_id;
1818 array_unshift($condition, $query);
1820 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1821 $statuses = Post::selectForUser($uid, [], $condition, $params);
1823 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1826 while ($status = DBA::fetch($statuses)) {
1827 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1829 DBA::close($statuses);
1831 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1834 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1835 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1838 * Returns the most recent statuses posted by the user.
1840 * @param string $type Either "json" or "xml"
1841 * @return string|array
1842 * @throws BadRequestException
1843 * @throws ForbiddenException
1844 * @throws ImagickException
1845 * @throws InternalServerErrorException
1846 * @throws UnauthorizedException
1847 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1849 function api_statuses_user_timeline($type)
1851 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1852 $uid = BaseApi::getCurrentUserID();
1854 Logger::info('api_statuses_user_timeline', ['api_user' => $uid, '_REQUEST' => $_REQUEST]);
1856 $cid = BaseApi::getContactIDForSearchterm($_REQUEST['screen_name'] ?? '', $_REQUEST['user_id'] ?? 0, $uid);
1857 $since_id = $_REQUEST['since_id'] ?? 0;
1858 $max_id = $_REQUEST['max_id'] ?? 0;
1859 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1860 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1863 $count = $_REQUEST['count'] ?? 20;
1864 $page = $_REQUEST['page'] ?? 1;
1866 $start = max(0, ($page - 1) * $count);
1868 $condition = ["(`uid` = ? OR (`uid` = ? AND NOT `global`)) AND `gravity` IN (?, ?) AND `id` > ? AND `author-id` = ?",
1869 0, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $cid];
1871 if ($exclude_replies) {
1872 $condition[0] .= ' AND `gravity` = ?';
1873 $condition[] = GRAVITY_PARENT;
1876 if ($conversation_id > 0) {
1877 $condition[0] .= " AND `parent` = ?";
1878 $condition[] = $conversation_id;
1882 $condition[0] .= " AND `id` <= ?";
1883 $condition[] = $max_id;
1885 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1886 $statuses = Post::selectForUser($uid, [], $condition, $params);
1888 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1891 while ($status = DBA::fetch($statuses)) {
1892 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1894 DBA::close($statuses);
1896 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1899 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1902 * Star/unstar an item.
1903 * param: id : id of the item
1905 * @param string $type Return type (atom, rss, xml, json)
1907 * @return array|string
1908 * @throws BadRequestException
1909 * @throws ForbiddenException
1910 * @throws ImagickException
1911 * @throws InternalServerErrorException
1912 * @throws UnauthorizedException
1913 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1915 function api_favorites_create_destroy($type)
1917 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1918 $uid = BaseApi::getCurrentUserID();
1920 // for versioned api.
1921 /// @TODO We need a better global soluton
1922 $action_argv_id = 2;
1923 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1924 $action_argv_id = 3;
1927 if (DI::args()->getArgc() <= $action_argv_id) {
1928 throw new BadRequestException("Invalid request.");
1930 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1931 if (DI::args()->getArgc() == $action_argv_id + 2) {
1932 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1934 $itemid = intval($_REQUEST['id'] ?? 0);
1937 $item = Post::selectFirstForUser($uid, [], ['id' => $itemid, 'uid' => $uid]);
1939 if (!DBA::isResult($item)) {
1940 throw new BadRequestException("Invalid item.");
1945 $item['starred'] = 1;
1948 $item['starred'] = 0;
1951 throw new BadRequestException("Invalid action ".$action);
1954 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1957 throw new InternalServerErrorException("DB error");
1960 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1962 $ret = DI::twitterStatus()->createFromUriId($item['uri-id'], $item['uid'], $include_entities)->toArray();
1964 return DI::apiResponse()->formatData("status", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1967 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1968 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1971 * Returns the most recent favorite statuses.
1973 * @param string $type Return type (atom, rss, xml, json)
1975 * @return string|array
1976 * @throws BadRequestException
1977 * @throws ForbiddenException
1978 * @throws ImagickException
1979 * @throws InternalServerErrorException
1980 * @throws UnauthorizedException
1982 function api_favorites($type)
1984 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1985 $uid = BaseApi::getCurrentUserID();
1987 // in friendica starred item are private
1988 // return favorites only for self
1989 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites']);
1992 $since_id = $_REQUEST['since_id'] ?? 0;
1993 $max_id = $_REQUEST['max_id'] ?? 0;
1994 $count = $_GET['count'] ?? 20;
1995 $page = $_REQUEST['page'] ?? 1;
1997 $start = max(0, ($page - 1) * $count);
1999 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2000 $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2002 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2005 $condition[0] .= " AND `id` <= ?";
2006 $condition[] = $max_id;
2009 $statuses = Post::selectForUser($uid, [], $condition, $params);
2011 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
2014 while ($status = DBA::fetch($statuses)) {
2015 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
2017 DBA::close($statuses);
2019 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
2022 api_register_func('api/favorites', 'api_favorites', true);
2025 * Returns all lists the user subscribes to.
2027 * @param string $type Return type (atom, rss, xml, json)
2029 * @return array|string
2030 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2032 function api_lists_list($type)
2035 /// @TODO $ret is not filled here?
2036 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2039 api_register_func('api/lists/list', 'api_lists_list', true);
2040 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2043 * Returns all groups the user owns.
2045 * @param string $type Return type (atom, rss, xml, json)
2047 * @return array|string
2048 * @throws BadRequestException
2049 * @throws ForbiddenException
2050 * @throws ImagickException
2051 * @throws InternalServerErrorException
2052 * @throws UnauthorizedException
2053 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2055 function api_lists_ownerships($type)
2057 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2058 $uid = BaseApi::getCurrentUserID();
2061 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2063 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2065 // loop through all groups
2067 foreach ($groups as $group) {
2068 if ($group['visible']) {
2074 'name' => $group['name'],
2075 'id' => intval($group['id']),
2076 'id_str' => (string) $group['id'],
2077 'user' => $user_info,
2081 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2084 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2087 * Returns recent statuses from users in the specified group.
2089 * @param string $type Return type (atom, rss, xml, json)
2091 * @return array|string
2092 * @throws BadRequestException
2093 * @throws ForbiddenException
2094 * @throws ImagickException
2095 * @throws InternalServerErrorException
2096 * @throws UnauthorizedException
2097 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2099 function api_lists_statuses($type)
2101 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2102 $uid = BaseApi::getCurrentUserID();
2104 unset($_REQUEST['user_id']);
2105 unset($_GET['user_id']);
2107 unset($_REQUEST['screen_name']);
2108 unset($_GET['screen_name']);
2110 if (empty($_REQUEST['list_id'])) {
2111 throw new BadRequestException('list_id not specified');
2115 $count = $_REQUEST['count'] ?? 20;
2116 $page = $_REQUEST['page'] ?? 1;
2117 $since_id = $_REQUEST['since_id'] ?? 0;
2118 $max_id = $_REQUEST['max_id'] ?? 0;
2119 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2120 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2122 $start = max(0, ($page - 1) * $count);
2124 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2125 $gids = array_column($groups, 'contact-id');
2126 $condition = ['uid' => $uid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2127 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2130 $condition[0] .= " AND `id` <= ?";
2131 $condition[] = $max_id;
2133 if ($exclude_replies > 0) {
2134 $condition[0] .= ' AND `gravity` = ?';
2135 $condition[] = GRAVITY_PARENT;
2137 if ($conversation_id > 0) {
2138 $condition[0] .= " AND `parent` = ?";
2139 $condition[] = $conversation_id;
2142 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2143 $statuses = Post::selectForUser($uid, [], $condition, $params);
2145 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
2148 while ($status = DBA::fetch($statuses)) {
2149 $items[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
2151 DBA::close($statuses);
2153 return DI::apiResponse()->formatData("statuses", $type, ['status' => $items], Contact::getPublicIdByUserId($uid));
2156 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2159 * Returns either the friends of the follower list
2161 * Considers friends and followers lists to be private and won't return
2162 * anything if any user_id parameter is passed.
2164 * @param string $qtype Either "friends" or "followers"
2165 * @return boolean|array
2166 * @throws BadRequestException
2167 * @throws ForbiddenException
2168 * @throws ImagickException
2169 * @throws InternalServerErrorException
2170 * @throws UnauthorizedException
2172 function api_statuses_f($qtype)
2174 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2175 $uid = BaseApi::getCurrentUserID();
2178 $count = $_GET['count'] ?? 20;
2179 $page = $_GET['page'] ?? 1;
2181 $start = max(0, ($page - 1) * $count);
2183 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2184 /* this is to stop Hotot to load friends multiple times
2185 * I'm not sure if I'm missing return something or
2186 * is a bug in hotot. Workaround, meantime
2190 return array('$users' => $ret);*/
2195 if ($qtype == 'friends') {
2196 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2197 } elseif ($qtype == 'followers') {
2198 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2201 if ($qtype == 'blocks') {
2202 $sql_filter = 'AND `blocked` AND NOT `pending`';
2203 } elseif ($qtype == 'incoming') {
2204 $sql_filter = 'AND `pending`';
2206 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2209 // @todo This query most likely can be replaced with a Contact::select...
2210 $r = DBA::toArray(DBA::p(
2225 foreach ($r as $cid) {
2226 $user = DI::twitterUser()->createFromContactId($cid['id'], $uid, false)->toArray();
2227 // "uid" is only needed for some internal stuff, so remove it from here
2228 unset($user['uid']);
2235 return ['user' => $ret];
2239 * Returns the list of friends of the provided user
2241 * @deprecated By Twitter API in favor of friends/list
2243 * @param string $type Either "json" or "xml"
2244 * @return boolean|string|array
2245 * @throws BadRequestException
2246 * @throws ForbiddenException
2248 function api_statuses_friends($type)
2250 $data = api_statuses_f("friends");
2251 if ($data === false) {
2254 return DI::apiResponse()->formatData("users", $type, $data);
2257 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2260 * Returns the list of followers of the provided user
2262 * @deprecated By Twitter API in favor of friends/list
2264 * @param string $type Either "json" or "xml"
2265 * @return boolean|string|array
2266 * @throws BadRequestException
2267 * @throws ForbiddenException
2269 function api_statuses_followers($type)
2271 $data = api_statuses_f("followers");
2272 if ($data === false) {
2275 return DI::apiResponse()->formatData("users", $type, $data);
2278 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2281 * Returns the list of blocked users
2283 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
2285 * @param string $type Either "json" or "xml"
2287 * @return boolean|string|array
2288 * @throws BadRequestException
2289 * @throws ForbiddenException
2291 function api_blocks_list($type)
2293 $data = api_statuses_f('blocks');
2294 if ($data === false) {
2297 return DI::apiResponse()->formatData("users", $type, $data);
2300 api_register_func('api/blocks/list', 'api_blocks_list', true);
2303 * Returns the list of pending users IDs
2305 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
2307 * @param string $type Either "json" or "xml"
2309 * @return boolean|string|array
2310 * @throws BadRequestException
2311 * @throws ForbiddenException
2313 function api_friendships_incoming($type)
2315 $data = api_statuses_f('incoming');
2316 if ($data === false) {
2321 foreach ($data['user'] as $user) {
2322 $ids[] = $user['id'];
2325 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
2328 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
2331 * Sends a new direct message.
2333 * @param string $type Return type (atom, rss, xml, json)
2335 * @return array|string
2336 * @throws BadRequestException
2337 * @throws ForbiddenException
2338 * @throws ImagickException
2339 * @throws InternalServerErrorException
2340 * @throws NotFoundException
2341 * @throws UnauthorizedException
2342 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
2344 function api_direct_messages_new($type)
2346 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2347 $uid = BaseApi::getCurrentUserID();
2349 if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
2353 $sender = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2355 $cid = BaseApi::getContactIDForSearchterm($_POST['screen_name'] ?? '', $_POST['user_id'] ?? 0, $uid);
2357 throw new NotFoundException('Recipient not found');
2361 if (!empty($_REQUEST['replyto'])) {
2362 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
2363 $replyto = $mail['parent-uri'];
2364 $sub = $mail['title'];
2366 if (!empty($_REQUEST['title'])) {
2367 $sub = $_REQUEST['title'];
2369 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
2373 $cdata = Contact::getPublicAndUserContactID($cid, $uid);
2375 $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
2378 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
2379 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid, true)->toArray(), $sender);
2381 $ret = ["error" => $id];
2384 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2387 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
2390 * delete a direct_message from mail table through api
2392 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2393 * @return string|array
2394 * @throws BadRequestException
2395 * @throws ForbiddenException
2396 * @throws ImagickException
2397 * @throws InternalServerErrorException
2398 * @throws UnauthorizedException
2399 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
2401 function api_direct_messages_destroy($type)
2403 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2404 $uid = BaseApi::getCurrentUserID();
2407 $id = $_REQUEST['id'] ?? 0;
2409 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
2410 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
2411 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
2413 // error if no id or parenturi specified (for clients posting parent-uri as well)
2414 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
2415 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
2416 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2419 // BadRequestException if no id specified (for clients using Twitter API)
2421 throw new BadRequestException('Message id not specified');
2424 // add parent-uri to sql command if specified by calling app
2425 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
2427 // error message if specified id is not in database
2428 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
2429 if ($verbose == "true") {
2430 $answer = ['result' => 'error', 'message' => 'message id not in database'];
2431 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2433 /// @todo BadRequestException ok for Twitter API clients?
2434 throw new BadRequestException('message id not in database');
2438 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
2440 if ($verbose == "true") {
2443 $answer = ['result' => 'ok', 'message' => 'message deleted'];
2444 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
2446 $answer = ['result' => 'error', 'message' => 'unknown error'];
2447 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2450 /// @todo return JSON data like Twitter API not yet implemented
2453 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2458 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2459 * @return string|array
2460 * @throws HTTPException\BadRequestException
2461 * @throws HTTPException\ExpectationFailedException
2462 * @throws HTTPException\ForbiddenException
2463 * @throws HTTPException\InternalServerErrorException
2464 * @throws HTTPException\NotFoundException
2465 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
2467 function api_friendships_destroy($type)
2469 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2470 $uid = BaseApi::getCurrentUserID();
2472 $owner = User::getOwnerDataById($uid);
2474 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
2475 throw new HTTPException\NotFoundException('Error Processing Request');
2478 $contact_id = $_REQUEST['user_id'] ?? 0;
2480 if (empty($contact_id)) {
2481 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
2482 throw new HTTPException\BadRequestException('no user_id specified');
2485 // Get Contact by given id
2486 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
2488 if(!DBA::isResult($contact)) {
2489 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
2490 throw new HTTPException\NotFoundException('no contact found to given ID');
2493 $url = $contact['url'];
2495 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
2496 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
2497 Strings::normaliseLink($url), $url];
2498 $contact = DBA::selectFirst('contact', [], $condition);
2500 if (!DBA::isResult($contact)) {
2501 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
2502 throw new HTTPException\NotFoundException('Not following Contact');
2506 $result = Contact::terminateFriendship($owner, $contact);
2508 if ($result === null) {
2509 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
2510 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
2513 if ($result === false) {
2514 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
2516 } catch (Exception $e) {
2517 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
2518 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
2521 // "uid" is only needed for some internal stuff, so remove it from here
2522 unset($contact['uid']);
2524 // Set screen_name since Twidere requests it
2525 $contact['screen_name'] = $contact['nick'];
2527 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
2530 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
2534 * @param string $type Return type (atom, rss, xml, json)
2535 * @param string $box
2536 * @param string $verbose
2538 * @return array|string
2539 * @throws BadRequestException
2540 * @throws ForbiddenException
2541 * @throws ImagickException
2542 * @throws InternalServerErrorException
2543 * @throws UnauthorizedException
2545 function api_direct_messages_box($type, $box, $verbose)
2547 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2548 $uid = BaseApi::getCurrentUserID();
2551 $count = $_GET['count'] ?? 20;
2552 $page = $_REQUEST['page'] ?? 1;
2554 $since_id = $_REQUEST['since_id'] ?? 0;
2555 $max_id = $_REQUEST['max_id'] ?? 0;
2557 $user_id = $_REQUEST['user_id'] ?? '';
2558 $screen_name = $_REQUEST['screen_name'] ?? '';
2561 unset($_REQUEST['user_id']);
2562 unset($_GET['user_id']);
2564 unset($_REQUEST['screen_name']);
2565 unset($_GET['screen_name']);
2567 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2569 $profile_url = $user_info["url"];
2572 $start = max(0, ($page - 1) * $count);
2577 if ($box=="sentbox") {
2578 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
2579 } elseif ($box == "conversation") {
2580 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
2581 } elseif ($box == "all") {
2582 $sql_extra = "true";
2583 } elseif ($box == "inbox") {
2584 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
2588 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
2591 if ($user_id != "") {
2592 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2593 } elseif ($screen_name !="") {
2594 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
2597 $r = DBA::toArray(DBA::p(
2598 "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 ?,?",
2604 if ($verbose == "true" && !DBA::isResult($r)) {
2605 $answer = ['result' => 'error', 'message' => 'no mails available'];
2606 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
2610 foreach ($r as $item) {
2611 if ($box == "inbox" || $item['from-url'] != $profile_url) {
2612 $recipient = $user_info;
2613 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2614 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
2615 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2616 $sender = $user_info;
2619 if (isset($recipient) && isset($sender)) {
2620 $ret[] = api_format_messages($item, $recipient, $sender);
2624 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2628 * Returns the most recent direct messages sent by the user.
2630 * @param string $type Return type (atom, rss, xml, json)
2632 * @return array|string
2633 * @throws BadRequestException
2634 * @throws ForbiddenException
2635 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
2637 function api_direct_messages_sentbox($type)
2639 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2640 return api_direct_messages_box($type, "sentbox", $verbose);
2643 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
2646 * Returns the most recent direct messages sent to the user.
2648 * @param string $type Return type (atom, rss, xml, json)
2650 * @return array|string
2651 * @throws BadRequestException
2652 * @throws ForbiddenException
2653 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
2655 function api_direct_messages_inbox($type)
2657 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2658 return api_direct_messages_box($type, "inbox", $verbose);
2661 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
2665 * @param string $type Return type (atom, rss, xml, json)
2667 * @return array|string
2668 * @throws BadRequestException
2669 * @throws ForbiddenException
2671 function api_direct_messages_all($type)
2673 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2674 return api_direct_messages_box($type, "all", $verbose);
2677 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
2681 * @param string $type Return type (atom, rss, xml, json)
2683 * @return array|string
2684 * @throws BadRequestException
2685 * @throws ForbiddenException
2687 function api_direct_messages_conversation($type)
2689 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2690 return api_direct_messages_box($type, "conversation", $verbose);
2693 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
2696 * list all photos of the authenticated user
2698 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2699 * @return string|array
2700 * @throws ForbiddenException
2701 * @throws InternalServerErrorException
2703 function api_fr_photos_list($type)
2705 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2706 $uid = BaseApi::getCurrentUserID();
2708 $r = DBA::toArray(DBA::p(
2709 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
2710 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
2711 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
2712 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
2715 'image/jpeg' => 'jpg',
2716 'image/png' => 'png',
2717 'image/gif' => 'gif'
2719 $data = ['photo'=>[]];
2720 if (DBA::isResult($r)) {
2721 foreach ($r as $rr) {
2723 $photo['id'] = $rr['resource-id'];
2724 $photo['album'] = $rr['album'];
2725 $photo['filename'] = $rr['filename'];
2726 $photo['type'] = $rr['type'];
2727 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
2728 $photo['created'] = $rr['created'];
2729 $photo['edited'] = $rr['edited'];
2730 $photo['desc'] = $rr['desc'];
2732 if ($type == "xml") {
2733 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
2735 $photo['thumb'] = $thumb;
2736 $data['photo'][] = $photo;
2740 return DI::apiResponse()->formatData("photos", $type, $data);
2743 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2746 * upload a new photo or change an existing photo
2748 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2749 * @return string|array
2750 * @throws BadRequestException
2751 * @throws ForbiddenException
2752 * @throws ImagickException
2753 * @throws InternalServerErrorException
2754 * @throws NotFoundException
2756 function api_fr_photo_create_update($type)
2758 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2759 $uid = BaseApi::getCurrentUserID();
2762 $photo_id = $_REQUEST['photo_id'] ?? null;
2763 $desc = $_REQUEST['desc'] ?? null;
2764 $album = $_REQUEST['album'] ?? null;
2765 $album_new = $_REQUEST['album_new'] ?? null;
2766 $allow_cid = $_REQUEST['allow_cid'] ?? null;
2767 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
2768 $allow_gid = $_REQUEST['allow_gid'] ?? null;
2769 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
2770 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
2772 // do several checks on input parameters
2773 // we do not allow calls without album string
2774 if ($album == null) {
2775 throw new BadRequestException("no albumname specified");
2777 // if photo_id == null --> we are uploading a new photo
2778 if ($photo_id == null) {
2781 // error if no media posted in create-mode
2782 if (empty($_FILES['media'])) {
2784 throw new BadRequestException("no media data submitted");
2787 // album_new will be ignored in create-mode
2792 // check if photo is existing in databasei
2793 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
2794 throw new BadRequestException("photo not available");
2798 // checks on acl strings provided by clients
2799 $acl_input_error = false;
2800 $acl_input_error |= check_acl_input($allow_cid, $uid);
2801 $acl_input_error |= check_acl_input($deny_cid, $uid);
2802 $acl_input_error |= check_acl_input($allow_gid, $uid);
2803 $acl_input_error |= check_acl_input($deny_gid, $uid);
2804 if ($acl_input_error) {
2805 throw new BadRequestException("acl data invalid");
2807 // now let's upload the new media in create-mode
2808 if ($mode == "create") {
2809 $media = $_FILES['media'];
2810 $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);
2812 // return success of updating or error message
2813 if (!is_null($data)) {
2814 return DI::apiResponse()->formatData("photo_create", $type, $data);
2816 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
2820 // now let's do the changes in update-mode
2821 if ($mode == "update") {
2822 $updated_fields = [];
2824 if (!is_null($desc)) {
2825 $updated_fields['desc'] = $desc;
2828 if (!is_null($album_new)) {
2829 $updated_fields['album'] = $album_new;
2832 if (!is_null($allow_cid)) {
2833 $allow_cid = trim($allow_cid);
2834 $updated_fields['allow_cid'] = $allow_cid;
2837 if (!is_null($deny_cid)) {
2838 $deny_cid = trim($deny_cid);
2839 $updated_fields['deny_cid'] = $deny_cid;
2842 if (!is_null($allow_gid)) {
2843 $allow_gid = trim($allow_gid);
2844 $updated_fields['allow_gid'] = $allow_gid;
2847 if (!is_null($deny_gid)) {
2848 $deny_gid = trim($deny_gid);
2849 $updated_fields['deny_gid'] = $deny_gid;
2853 if (count($updated_fields) > 0) {
2854 $nothingtodo = false;
2855 $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
2857 $nothingtodo = true;
2860 if (!empty($_FILES['media'])) {
2861 $nothingtodo = false;
2862 $media = $_FILES['media'];
2863 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
2864 if (!is_null($data)) {
2865 return DI::apiResponse()->formatData("photo_update", $type, $data);
2869 // return success of updating or error message
2871 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
2872 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
2875 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
2876 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
2878 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
2881 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
2884 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
2885 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
2888 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
2890 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2891 * @return string|array
2892 * @throws BadRequestException
2893 * @throws ForbiddenException
2894 * @throws InternalServerErrorException
2895 * @throws NotFoundException
2897 function api_fr_photo_detail($type)
2899 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2900 $uid = BaseApi::getCurrentUserID();
2902 if (empty($_REQUEST['photo_id'])) {
2903 throw new BadRequestException("No photo id.");
2906 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
2907 $photo_id = $_REQUEST['photo_id'];
2909 // prepare json/xml output with data from database for the requested photo
2910 $data = prepare_photo_data($type, $scale, $photo_id, $uid);
2912 return DI::apiResponse()->formatData("photo_detail", $type, $data);
2915 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2918 * updates the profile image for the user (either a specified profile or the default profile)
2920 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2922 * @return string|array
2923 * @throws BadRequestException
2924 * @throws ForbiddenException
2925 * @throws ImagickException
2926 * @throws InternalServerErrorException
2927 * @throws NotFoundException
2928 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
2930 function api_account_update_profile_image($type)
2932 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2933 $uid = BaseApi::getCurrentUserID();
2936 $profile_id = $_REQUEST['profile_id'] ?? 0;
2938 // error if image data is missing
2939 if (empty($_FILES['image'])) {
2940 throw new BadRequestException("no media data submitted");
2943 // check if specified profile id is valid
2944 if ($profile_id != 0) {
2945 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
2946 // error message if specified profile id is not in database
2947 if (!DBA::isResult($profile)) {
2948 throw new BadRequestException("profile_id not available");
2950 $is_default_profile = $profile['is-default'];
2952 $is_default_profile = 1;
2955 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
2957 if (!empty($_FILES['image'])) {
2958 $media = $_FILES['image'];
2959 } elseif (!empty($_FILES['media'])) {
2960 $media = $_FILES['media'];
2962 // save new profile image
2963 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
2966 if (is_array($media['type'])) {
2967 $filetype = $media['type'][0];
2969 $filetype = $media['type'];
2971 if ($filetype == "image/jpeg") {
2973 } elseif ($filetype == "image/png") {
2976 throw new InternalServerErrorException('Unsupported filetype');
2979 // change specified profile or all profiles to the new resource-id
2980 if ($is_default_profile) {
2981 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
2982 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
2984 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
2985 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
2986 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
2989 Contact::updateSelfFromUserID($uid, true);
2991 // Update global directory in background
2992 Profile::publishUpdate($uid);
2994 // output for client
2996 return api_account_verify_credentials($type);
2998 // SaveMediaToDatabase failed for some reason
2999 throw new InternalServerErrorException("image upload failed");
3003 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3006 * Update user profile
3008 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3010 * @return array|string
3011 * @throws BadRequestException
3012 * @throws ForbiddenException
3013 * @throws ImagickException
3014 * @throws InternalServerErrorException
3015 * @throws UnauthorizedException
3017 function api_account_update_profile($type)
3019 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3020 $uid = BaseApi::getCurrentUserID();
3022 $api_user = DI::twitterUser()->createFromUserId($uid, true)->toArray();
3024 if (!empty($_POST['name'])) {
3025 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $uid]);
3026 DBA::update('user', ['username' => $_POST['name']], ['uid' => $uid]);
3027 Contact::update(['name' => $_POST['name']], ['uid' => $uid, 'self' => 1]);
3028 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3031 if (isset($_POST['description'])) {
3032 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $uid]);
3033 Contact::update(['about' => $_POST['description']], ['uid' => $uid, 'self' => 1]);
3034 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3037 Profile::publishUpdate($uid);
3039 return api_account_verify_credentials($type);
3042 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3045 * Return all or a specified group of the user with the containing contacts.
3047 * @param string $type Return type (atom, rss, xml, json)
3049 * @return array|string
3050 * @throws BadRequestException
3051 * @throws ForbiddenException
3052 * @throws ImagickException
3053 * @throws InternalServerErrorException
3054 * @throws UnauthorizedException
3056 function api_friendica_group_show($type)
3058 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3059 $uid = BaseApi::getCurrentUserID();
3062 $gid = $_REQUEST['gid'] ?? 0;
3064 // get data of the specified group id or all groups if not specified
3066 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
3068 // error message if specified gid is not in database
3069 if (!DBA::isResult($groups)) {
3070 throw new BadRequestException("gid not available");
3073 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
3076 // loop through all groups and retrieve all members for adding data in the user array
3078 foreach ($groups as $rr) {
3079 $members = Contact\Group::getById($rr['id']);
3082 if ($type == "xml") {
3083 $user_element = "users";
3085 foreach ($members as $member) {
3086 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
3087 $users[$k++.":user"] = $user;
3090 $user_element = "user";
3091 foreach ($members as $member) {
3092 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
3096 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
3098 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
3101 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3106 * @param string $type Return type (atom, rss, xml, json)
3108 * @return array|string
3109 * @throws BadRequestException
3110 * @throws ForbiddenException
3111 * @throws ImagickException
3112 * @throws InternalServerErrorException
3113 * @throws UnauthorizedException
3114 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
3116 function api_lists_destroy($type)
3118 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3119 $uid = BaseApi::getCurrentUserID();
3122 $gid = $_REQUEST['list_id'] ?? 0;
3124 // error if no gid specified
3126 throw new BadRequestException('gid not specified');
3129 // get data of the specified group id
3130 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
3131 // error message if specified gid is not in database
3133 throw new BadRequestException('gid not available');
3136 if (Group::remove($gid)) {
3138 'name' => $group['name'],
3139 'id' => intval($gid),
3140 'id_str' => (string) $gid,
3141 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
3144 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
3148 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
3151 * Create the specified group with the posted array of contacts.
3153 * @param string $type Return type (atom, rss, xml, json)
3155 * @return array|string
3156 * @throws BadRequestException
3157 * @throws ForbiddenException
3158 * @throws ImagickException
3159 * @throws InternalServerErrorException
3160 * @throws UnauthorizedException
3162 function api_friendica_group_create($type)
3164 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3165 $uid = BaseApi::getCurrentUserID();
3168 $name = $_REQUEST['name'] ?? '';
3169 $json = json_decode($_POST['json'], true);
3170 $users = $json['user'];
3172 $success = group_create($name, $uid, $users);
3174 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
3177 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3180 * Create a new group.
3182 * @param string $type Return type (atom, rss, xml, json)
3184 * @return array|string
3185 * @throws BadRequestException
3186 * @throws ForbiddenException
3187 * @throws ImagickException
3188 * @throws InternalServerErrorException
3189 * @throws UnauthorizedException
3190 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
3192 function api_lists_create($type)
3194 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3195 $uid = BaseApi::getCurrentUserID();
3198 $name = $_REQUEST['name'] ?? '';
3200 $success = group_create($name, $uid);
3201 if ($success['success']) {
3203 'name' => $success['name'],
3204 'id' => intval($success['gid']),
3205 'id_str' => (string) $success['gid'],
3206 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
3209 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
3213 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
3216 * Update the specified group with the posted array of contacts.
3218 * @param string $type Return type (atom, rss, xml, json)
3220 * @return array|string
3221 * @throws BadRequestException
3222 * @throws ForbiddenException
3223 * @throws ImagickException
3224 * @throws InternalServerErrorException
3225 * @throws UnauthorizedException
3227 function api_friendica_group_update($type)
3229 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3230 $uid = BaseApi::getCurrentUserID();
3233 $gid = $_REQUEST['gid'] ?? 0;
3234 $name = $_REQUEST['name'] ?? '';
3235 $json = json_decode($_POST['json'], true);
3236 $users = $json['user'];
3238 // error if no name specified
3240 throw new BadRequestException('group name not specified');
3243 // error if no gid specified
3245 throw new BadRequestException('gid not specified');
3249 $members = Contact\Group::getById($gid);
3250 foreach ($members as $member) {
3251 $cid = $member['id'];
3252 foreach ($users as $user) {
3253 $found = ($user['cid'] == $cid ? true : false);
3255 if (!isset($found) || !$found) {
3256 $gid = Group::getIdByName($uid, $name);
3257 Group::removeMember($gid, $cid);
3262 $erroraddinguser = false;
3264 foreach ($users as $user) {
3265 $cid = $user['cid'];
3267 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
3268 Group::addMember($gid, $cid);
3270 $erroraddinguser = true;
3271 $errorusers[] = $cid;
3275 // return success message incl. missing users in array
3276 $status = ($erroraddinguser ? "missing user" : "ok");
3277 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
3278 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
3281 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3284 * Update information about a group.
3286 * @param string $type Return type (atom, rss, xml, json)
3288 * @return array|string
3289 * @throws BadRequestException
3290 * @throws ForbiddenException
3291 * @throws ImagickException
3292 * @throws InternalServerErrorException
3293 * @throws UnauthorizedException
3294 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
3296 function api_lists_update($type)
3298 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3299 $uid = BaseApi::getCurrentUserID();
3302 $gid = $_REQUEST['list_id'] ?? 0;
3303 $name = $_REQUEST['name'] ?? '';
3305 // error if no gid specified
3307 throw new BadRequestException('gid not specified');
3310 // get data of the specified group id
3311 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
3312 // error message if specified gid is not in database
3314 throw new BadRequestException('gid not available');
3317 if (Group::update($gid, $name)) {
3320 'id' => intval($gid),
3321 'id_str' => (string) $gid,
3322 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
3325 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
3329 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
3332 * Set notification as seen and returns associated item (if possible)
3334 * POST request with 'id' param as notification id
3336 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3337 * @return string|array
3338 * @throws BadRequestException
3339 * @throws ForbiddenException
3340 * @throws ImagickException
3341 * @throws InternalServerErrorException
3342 * @throws UnauthorizedException
3344 function api_friendica_notification_seen($type)
3346 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3347 $uid = BaseApi::getCurrentUserID();
3349 if (DI::args()->getArgc() !== 4) {
3350 throw new BadRequestException('Invalid argument count');
3353 $id = intval($_REQUEST['id'] ?? 0);
3356 $Notify = DI::notify()->selectOneById($id);
3357 if ($Notify->uid !== $uid) {
3358 throw new NotFoundException();
3361 if ($Notify->uriId) {
3362 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
3366 DI::notify()->save($Notify);
3368 if ($Notify->otype === Notification\ObjectType::ITEM) {
3369 $item = Post::selectFirstForUser($uid, [], ['id' => $Notify->iid, 'uid' => $uid]);
3370 if (DBA::isResult($item)) {
3371 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
3373 // we found the item, return it to the user
3374 $ret = [DI::twitterStatus()->createFromUriId($item['uri-id'], $item['uid'], $include_entities)->toArray()];
3375 $data = ['status' => $ret];
3376 return DI::apiResponse()->formatData('status', $type, $data);
3378 // the item can't be found, but we set the notification as seen, so we count this as a success
3381 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
3382 } catch (NotFoundException $e) {
3383 throw new BadRequestException('Invalid argument', $e);
3384 } catch (Exception $e) {
3385 throw new InternalServerErrorException('Internal Server exception', $e);
3389 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3392 * search for direct_messages containing a searchstring through api
3394 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3395 * @param string $box
3396 * @return string|array (success: success=true if found and search_result contains found messages,
3397 * success=false if nothing was found, search_result='nothing found',
3398 * error: result=error with error message)
3399 * @throws BadRequestException
3400 * @throws ForbiddenException
3401 * @throws ImagickException
3402 * @throws InternalServerErrorException
3403 * @throws UnauthorizedException
3405 function api_friendica_direct_messages_search($type, $box = "")
3407 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3408 $uid = BaseApi::getCurrentUserID();
3411 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
3412 $searchstring = $_REQUEST['searchstring'] ?? '';
3414 // error if no searchstring specified
3415 if ($searchstring == "") {
3416 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
3417 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
3420 // get data for the specified searchstring
3421 $r = DBA::toArray(DBA::p(
3422 "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",
3424 '%'.$searchstring.'%'
3427 $profile_url = $user_info["url"];
3429 // message if nothing was found
3430 if (!DBA::isResult($r)) {
3431 $success = ['success' => false, 'search_results' => 'problem with query'];
3432 } elseif (count($r) == 0) {
3433 $success = ['success' => false, 'search_results' => 'nothing found'];
3436 foreach ($r as $item) {
3437 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3438 $recipient = $user_info;
3439 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
3440 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3441 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
3442 $sender = $user_info;
3445 if (isset($recipient) && isset($sender)) {
3446 $ret[] = api_format_messages($item, $recipient, $sender);
3449 $success = ['success' => true, 'search_results' => $ret];
3452 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
3455 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);