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];
687 * Get data from $_POST or $_GET
692 function requestdata($k)
694 if (!empty($_POST[$k])) {
697 if (!empty($_GET[$k])) {
708 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
709 * returns a 401 status code and an error message if not.
711 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
713 * @param string $type Return type (atom, rss, xml, json)
714 * @return array|string
715 * @throws BadRequestException
716 * @throws ForbiddenException
717 * @throws ImagickException
718 * @throws InternalServerErrorException
719 * @throws UnauthorizedException
721 function api_account_verify_credentials($type)
723 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
724 $uid = BaseApi::getCurrentUserID();
726 unset($_REQUEST['user_id']);
727 unset($_GET['user_id']);
729 unset($_REQUEST['screen_name']);
730 unset($_GET['screen_name']);
732 $skip_status = $_REQUEST['skip_status'] ?? false;
734 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
736 // "verified" isn't used here in the standard
737 unset($user_info["verified"]);
739 // "uid" is only needed for some internal stuff, so remove it from here
740 unset($user_info['uid']);
742 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
745 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
748 * Deprecated function to upload media.
750 * @param string $type Return type (atom, rss, xml, json)
752 * @return array|string
753 * @throws BadRequestException
754 * @throws ForbiddenException
755 * @throws ImagickException
756 * @throws InternalServerErrorException
757 * @throws UnauthorizedException
759 function api_statuses_mediap($type)
761 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
762 $uid = BaseApi::getCurrentUserID();
766 $_REQUEST['profile_uid'] = $uid;
767 $_REQUEST['api_source'] = true;
768 $txt = requestdata('status') ?? '';
770 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
771 $txt = HTML::toBBCodeVideo($txt);
772 $config = HTMLPurifier_Config::createDefault();
773 $config->set('Cache.DefinitionImpl', null);
774 $purifier = new HTMLPurifier($config);
775 $txt = $purifier->purify($txt);
777 $txt = HTML::toBBCode($txt);
779 $picture = wall_upload_post($a, false);
781 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
782 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
783 $item_id = item_post($a);
785 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
787 // output the post that we just posted.
788 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
789 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
792 /// @TODO move this to top of file or somewhere better!
793 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
796 * Updates the user’s current status.
798 * @param string $type Return type (atom, rss, xml, json)
800 * @return array|string
801 * @throws BadRequestException
802 * @throws ForbiddenException
803 * @throws ImagickException
804 * @throws InternalServerErrorException
805 * @throws TooManyRequestsException
806 * @throws UnauthorizedException
807 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
809 function api_statuses_update($type)
811 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
812 $uid = BaseApi::getCurrentUserID();
816 // convert $_POST array items to the form we use for web posts.
817 if (requestdata('htmlstatus')) {
818 $txt = requestdata('htmlstatus') ?? '';
819 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
820 $txt = HTML::toBBCodeVideo($txt);
822 $config = HTMLPurifier_Config::createDefault();
823 $config->set('Cache.DefinitionImpl', null);
825 $purifier = new HTMLPurifier($config);
826 $txt = $purifier->purify($txt);
828 $_REQUEST['body'] = HTML::toBBCode($txt);
831 $_REQUEST['body'] = requestdata('status');
834 $_REQUEST['title'] = requestdata('title');
836 $parent = requestdata('in_reply_to_status_id');
838 // Twidere sends "-1" if it is no reply ...
843 if (ctype_digit($parent)) {
844 $_REQUEST['parent'] = $parent;
846 $_REQUEST['parent_uri'] = $parent;
849 if (requestdata('lat') && requestdata('long')) {
850 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
852 $_REQUEST['profile_uid'] = $uid;
855 // Check for throttling (maximum posts per day, week and month)
856 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
857 if ($throttle_day > 0) {
858 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
860 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
861 $posts_day = Post::count($condition);
863 if ($posts_day > $throttle_day) {
864 logger::info('Daily posting limit reached for user ' . $uid);
865 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
866 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));
870 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
871 if ($throttle_week > 0) {
872 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
874 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
875 $posts_week = Post::count($condition);
877 if ($posts_week > $throttle_week) {
878 logger::info('Weekly posting limit reached for user ' . $uid);
879 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
880 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));
884 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
885 if ($throttle_month > 0) {
886 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
888 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
889 $posts_month = Post::count($condition);
891 if ($posts_month > $throttle_month) {
892 logger::info('Monthly posting limit reached for user ' . $uid);
893 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
894 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));
899 if (requestdata('media_ids')) {
900 $ids = explode(',', requestdata('media_ids') ?? '');
901 } elseif (!empty($_FILES['media'])) {
902 // upload the image if we have one
903 $picture = wall_upload_post($a, false);
904 if (is_array($picture)) {
905 $ids[] = $picture['id'];
913 foreach ($ids as $id) {
914 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
915 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
916 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
917 ORDER BY `photo`.`width` DESC LIMIT 2", $id, $uid));
919 if (!empty($media)) {
920 $ressources[] = $media[0]['resource-id'];
921 $phototypes = Images::supportedTypes();
922 $ext = $phototypes[$media[0]['type']];
924 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
925 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
926 'size' => $media[0]['datasize'],
927 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
928 'description' => $media[0]['desc'] ?? '',
929 'width' => $media[0]['width'],
930 'height' => $media[0]['height']];
932 if (count($media) > 1) {
933 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
934 $attachment['preview-width'] = $media[1]['width'];
935 $attachment['preview-height'] = $media[1]['height'];
937 $attachments[] = $attachment;
941 // We have to avoid that the post is rejected because of an empty body
942 if (empty($_REQUEST['body'])) {
943 $_REQUEST['body'] = '[hr]';
947 if (!empty($attachments)) {
948 $_REQUEST['attachments'] = $attachments;
951 // set this so that the item_post() function is quiet and doesn't redirect or emit json
953 $_REQUEST['api_source'] = true;
955 if (empty($_REQUEST['source'])) {
956 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
959 // call out normal post function
960 $item_id = item_post($a);
962 if (!empty($ressources) && !empty($item_id)) {
963 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
964 foreach ($ressources as $ressource) {
965 Photo::setPermissionForRessource($ressource, $uid, $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
969 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
971 // output the post that we just posted.
972 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
973 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
976 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
977 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
980 * Uploads an image to Friendica.
983 * @throws BadRequestException
984 * @throws ForbiddenException
985 * @throws ImagickException
986 * @throws InternalServerErrorException
987 * @throws UnauthorizedException
988 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
990 function api_media_upload()
992 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
994 if (empty($_FILES['media'])) {
996 throw new BadRequestException("No media.");
999 $media = wall_upload_post(DI::app(), false);
1002 throw new InternalServerErrorException();
1006 $returndata["media_id"] = $media["id"];
1007 $returndata["media_id_string"] = (string)$media["id"];
1008 $returndata["size"] = $media["size"];
1009 $returndata["image"] = ["w" => $media["width"],
1010 "h" => $media["height"],
1011 "image_type" => $media["type"],
1012 "friendica_preview_url" => $media["preview"]];
1014 Logger::info('Media uploaded', ['return' => $returndata]);
1016 return ["media" => $returndata];
1019 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1022 * Updates media meta data (picture descriptions)
1024 * @param string $type Return type (atom, rss, xml, json)
1026 * @return array|string
1027 * @throws BadRequestException
1028 * @throws ForbiddenException
1029 * @throws ImagickException
1030 * @throws InternalServerErrorException
1031 * @throws TooManyRequestsException
1032 * @throws UnauthorizedException
1033 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1035 * @todo Compare the corresponding Twitter function for correct return values
1037 function api_media_metadata_create($type)
1039 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1040 $uid = BaseApi::getCurrentUserID();
1042 $postdata = Network::postdata();
1044 if (empty($postdata)) {
1045 throw new BadRequestException("No post data");
1048 $data = json_decode($postdata, true);
1050 throw new BadRequestException("Invalid post data");
1053 if (empty($data['media_id']) || empty($data['alt_text'])) {
1054 throw new BadRequestException("Missing post data values");
1057 if (empty($data['alt_text']['text'])) {
1058 throw new BadRequestException("No alt text.");
1061 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1063 $condition = ['id' => $data['media_id'], 'uid' => $uid];
1064 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1065 if (!DBA::isResult($photo)) {
1066 throw new BadRequestException("Metadata not found.");
1069 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1072 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1075 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1076 * The author's most recent status will be returned inline.
1078 * @param string $type Return type (atom, rss, xml, json)
1079 * @return array|string
1080 * @throws BadRequestException
1081 * @throws ImagickException
1082 * @throws InternalServerErrorException
1083 * @throws UnauthorizedException
1084 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1086 function api_users_show($type)
1088 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1089 $uid = BaseApi::getCurrentUserID();
1091 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
1094 'author-id'=> $user_info['pid'],
1096 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1097 'private' => [Item::PUBLIC, Item::UNLISTED]
1100 $item = Post::selectFirst(['uri-id', 'id'], $condition);
1101 if (!empty($item)) {
1102 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1103 $user_info['status'] = DI::twitterStatus()->createFromUriId($item['uri-id'], $item['uid'], $include_entities)->toArray();
1106 // "uid" is only needed for some internal stuff, so remove it from here
1107 unset($user_info['uid']);
1109 return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
1112 api_register_func('api/users/show', 'api_users_show');
1113 api_register_func('api/externalprofile/show', 'api_users_show');
1116 * Search a public user account.
1118 * @param string $type Return type (atom, rss, xml, json)
1120 * @return array|string
1121 * @throws BadRequestException
1122 * @throws ImagickException
1123 * @throws InternalServerErrorException
1124 * @throws UnauthorizedException
1125 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1127 function api_users_search($type)
1129 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1130 $uid = BaseApi::getCurrentUserID();
1134 if (!empty($_GET['q'])) {
1135 $contacts = Contact::selectToArray(
1138 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1146 if (DBA::isResult($contacts)) {
1148 foreach ($contacts as $contact) {
1149 $user_info = DI::twitterUser()->createFromContactId($contact['id'], $uid)->toArray();
1151 if ($type == 'xml') {
1152 $userlist[$k++ . ':user'] = $user_info;
1154 $userlist[] = $user_info;
1157 $userlist = ['users' => $userlist];
1159 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1162 throw new BadRequestException('No search term specified.');
1165 return DI::apiResponse()->formatData('users', $type, $userlist);
1168 api_register_func('api/users/search', 'api_users_search');
1171 * Return user objects
1173 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1175 * @param string $type Return format: json or xml
1177 * @return array|string
1178 * @throws BadRequestException
1179 * @throws ImagickException
1180 * @throws InternalServerErrorException
1181 * @throws NotFoundException if the results are empty.
1182 * @throws UnauthorizedException
1184 function api_users_lookup($type)
1186 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1187 $uid = BaseApi::getCurrentUserID();
1191 if (!empty($_REQUEST['user_id'])) {
1192 foreach (explode(',', $_REQUEST['user_id']) as $cid) {
1193 if (!empty($cid) && is_numeric($cid)) {
1194 $users[] = DI::twitterUser()->createFromContactId((int)$cid, $uid)->toArray();
1199 if (empty($users)) {
1200 throw new NotFoundException;
1203 return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
1206 api_register_func('api/users/lookup', 'api_users_lookup', true);
1209 * Returns statuses that match a specified query.
1211 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1213 * @param string $type Return format: json, xml, atom, rss
1215 * @return array|string
1216 * @throws BadRequestException if the "q" parameter is missing.
1217 * @throws ForbiddenException
1218 * @throws ImagickException
1219 * @throws InternalServerErrorException
1220 * @throws UnauthorizedException
1222 function api_search($type)
1224 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1225 $uid = BaseApi::getCurrentUserID();
1227 if (empty($_REQUEST['q'])) {
1228 throw new BadRequestException('q parameter is required.');
1231 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1234 $data['status'] = [];
1236 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1237 if (!empty($_REQUEST['rpp'])) {
1238 $count = $_REQUEST['rpp'];
1239 } elseif (!empty($_REQUEST['count'])) {
1240 $count = $_REQUEST['count'];
1243 $since_id = $_REQUEST['since_id'] ?? 0;
1244 $max_id = $_REQUEST['max_id'] ?? 0;
1245 $page = $_REQUEST['page'] ?? 1;
1247 $start = max(0, ($page - 1) * $count);
1249 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1250 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1251 $searchTerm = $matches[1];
1252 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, $uid];
1253 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1255 while ($tag = DBA::fetch($tags)) {
1256 $uriids[] = $tag['uri-id'];
1260 if (empty($uriids)) {
1261 return DI::apiResponse()->formatData('statuses', $type, $data);
1264 $condition = ['uri-id' => $uriids];
1265 if ($exclude_replies) {
1266 $condition['gravity'] = GRAVITY_PARENT;
1269 $params['group_by'] = ['uri-id'];
1271 $condition = ["`id` > ?
1272 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1273 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1274 AND `body` LIKE CONCAT('%',?,'%')",
1275 $since_id, $uid, $_REQUEST['q']];
1277 $condition[0] .= ' AND `id` <= ?';
1278 $condition[] = $max_id;
1284 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1285 $id = Item::fetchByLink($searchTerm, $uid);
1288 $id = Item::fetchByLink($searchTerm);
1292 $statuses = Post::select([], ['id' => $id]);
1296 $statuses = $statuses ?: Post::selectForUser($uid, [], $condition, $params);
1298 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1301 while ($status = DBA::fetch($statuses)) {
1302 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1304 DBA::close($statuses);
1306 $data['status'] = $ret;
1308 return DI::apiResponse()->formatData('statuses', $type, $data);
1311 api_register_func('api/search/tweets', 'api_search', true);
1312 api_register_func('api/search', 'api_search', true);
1315 * Returns the most recent statuses posted by the user and the users they follow.
1317 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1319 * @param string $type Return type (atom, rss, xml, json)
1321 * @return array|string
1322 * @throws BadRequestException
1323 * @throws ForbiddenException
1324 * @throws ImagickException
1325 * @throws InternalServerErrorException
1326 * @throws UnauthorizedException
1327 * @todo Optional parameters
1328 * @todo Add reply info
1330 function api_statuses_home_timeline($type)
1332 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1333 $uid = BaseApi::getCurrentUserID();
1335 unset($_REQUEST['user_id']);
1336 unset($_GET['user_id']);
1338 unset($_REQUEST['screen_name']);
1339 unset($_GET['screen_name']);
1341 // get last network messages
1344 $count = $_REQUEST['count'] ?? 20;
1345 $page = $_REQUEST['page']?? 0;
1346 $since_id = $_REQUEST['since_id'] ?? 0;
1347 $max_id = $_REQUEST['max_id'] ?? 0;
1348 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1349 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1351 $start = max(0, ($page - 1) * $count);
1353 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1354 $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1357 $condition[0] .= " AND `id` <= ?";
1358 $condition[] = $max_id;
1360 if ($exclude_replies) {
1361 $condition[0] .= ' AND `gravity` = ?';
1362 $condition[] = GRAVITY_PARENT;
1364 if ($conversation_id > 0) {
1365 $condition[0] .= " AND `parent` = ?";
1366 $condition[] = $conversation_id;
1369 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1370 $statuses = Post::selectForUser($uid, [], $condition, $params);
1372 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1376 while ($status = DBA::fetch($statuses)) {
1377 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1378 $idarray[] = intval($status['id']);
1380 DBA::close($statuses);
1382 if (!empty($idarray)) {
1383 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1385 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1389 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1393 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1394 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1397 * Returns the most recent statuses from public users.
1399 * @param string $type Return type (atom, rss, xml, json)
1401 * @return array|string
1402 * @throws BadRequestException
1403 * @throws ForbiddenException
1404 * @throws ImagickException
1405 * @throws InternalServerErrorException
1406 * @throws UnauthorizedException
1408 function api_statuses_public_timeline($type)
1410 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1411 $uid = BaseApi::getCurrentUserID();
1413 // get last network messages
1416 $count = $_REQUEST['count'] ?? 20;
1417 $page = $_REQUEST['page'] ?? 1;
1418 $since_id = $_REQUEST['since_id'] ?? 0;
1419 $max_id = $_REQUEST['max_id'] ?? 0;
1420 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1421 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1423 $start = max(0, ($page - 1) * $count);
1425 if ($exclude_replies && !$conversation_id) {
1426 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1427 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1430 $condition[0] .= " AND `id` <= ?";
1431 $condition[] = $max_id;
1434 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1435 $statuses = Post::selectForUser($uid, [], $condition, $params);
1437 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1438 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1441 $condition[0] .= " AND `id` <= ?";
1442 $condition[] = $max_id;
1444 if ($conversation_id > 0) {
1445 $condition[0] .= " AND `parent` = ?";
1446 $condition[] = $conversation_id;
1449 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1450 $statuses = Post::selectForUser($uid, [], $condition, $params);
1453 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1456 while ($status = DBA::fetch($statuses)) {
1457 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1459 DBA::close($statuses);
1461 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1464 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1467 * Returns the most recent statuses posted by users this node knows about.
1469 * @param string $type Return format: json, xml, atom, rss
1470 * @return array|string
1471 * @throws BadRequestException
1472 * @throws ForbiddenException
1473 * @throws ImagickException
1474 * @throws InternalServerErrorException
1475 * @throws UnauthorizedException
1477 function api_statuses_networkpublic_timeline($type)
1479 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1480 $uid = BaseApi::getCurrentUserID();
1482 $since_id = $_REQUEST['since_id'] ?? 0;
1483 $max_id = $_REQUEST['max_id'] ?? 0;
1486 $count = $_REQUEST['count'] ?? 20;
1487 $page = $_REQUEST['page'] ?? 1;
1489 $start = max(0, ($page - 1) * $count);
1491 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1492 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1495 $condition[0] .= " AND `id` <= ?";
1496 $condition[] = $max_id;
1499 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1500 $statuses = Post::selectForUser($uid, Item::DISPLAY_FIELDLIST, $condition, $params);
1502 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1505 while ($status = DBA::fetch($statuses)) {
1506 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1508 DBA::close($statuses);
1510 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1513 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1516 * Returns a single status.
1518 * @param string $type Return type (atom, rss, xml, json)
1520 * @return array|string
1521 * @throws BadRequestException
1522 * @throws ForbiddenException
1523 * @throws ImagickException
1524 * @throws InternalServerErrorException
1525 * @throws UnauthorizedException
1526 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1528 function api_statuses_show($type)
1530 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1531 $uid = BaseApi::getCurrentUserID();
1534 $id = intval(DI::args()->getArgv()[3] ?? 0);
1537 $id = intval($_REQUEST['id'] ?? 0);
1542 $id = intval(DI::args()->getArgv()[4] ?? 0);
1545 logger::notice('API: api_statuses_show: ' . $id);
1547 $conversation = !empty($_REQUEST['conversation']);
1549 // try to fetch the item for the local user - or the public item, if there is no local one
1550 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1551 if (!DBA::isResult($uri_item)) {
1552 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1555 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1556 if (!DBA::isResult($item)) {
1557 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1562 if ($conversation) {
1563 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1564 $params = ['order' => ['id' => true]];
1566 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1570 $statuses = Post::selectForUser($uid, [], $condition, $params);
1572 /// @TODO How about copying this to above methods which don't check $r ?
1573 if (!DBA::isResult($statuses)) {
1574 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1577 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1580 while ($status = DBA::fetch($statuses)) {
1581 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1583 DBA::close($statuses);
1585 if ($conversation) {
1586 $data = ['status' => $ret];
1587 return DI::apiResponse()->formatData("statuses", $type, $data);
1589 $data = ['status' => $ret[0]];
1590 return DI::apiResponse()->formatData("status", $type, $data);
1594 api_register_func('api/statuses/show', 'api_statuses_show', true);
1598 * @param string $type Return type (atom, rss, xml, json)
1600 * @return array|string
1601 * @throws BadRequestException
1602 * @throws ForbiddenException
1603 * @throws ImagickException
1604 * @throws InternalServerErrorException
1605 * @throws UnauthorizedException
1606 * @todo nothing to say?
1608 function api_conversation_show($type)
1610 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1611 $uid = BaseApi::getCurrentUserID();
1614 $id = intval(DI::args()->getArgv()[3] ?? 0);
1615 $since_id = intval($_REQUEST['since_id'] ?? 0);
1616 $max_id = intval($_REQUEST['max_id'] ?? 0);
1617 $count = intval($_REQUEST['count'] ?? 20);
1618 $page = intval($_REQUEST['page'] ?? 1);
1620 $start = max(0, ($page - 1) * $count);
1623 $id = intval($_REQUEST['id'] ?? 0);
1628 $id = intval(DI::args()->getArgv()[4] ?? 0);
1631 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1633 // try to fetch the item for the local user - or the public item, if there is no local one
1634 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1635 if (!DBA::isResult($item)) {
1636 throw new BadRequestException("There is no status with the id $id.");
1639 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1640 if (!DBA::isResult($parent)) {
1641 throw new BadRequestException("There is no status with this id.");
1644 $id = $parent['id'];
1646 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1647 $id, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1650 $condition[0] .= " AND `id` <= ?";
1651 $condition[] = $max_id;
1654 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1655 $statuses = Post::selectForUser($uid, [], $condition, $params);
1657 if (!DBA::isResult($statuses)) {
1658 throw new BadRequestException("There is no status with id $id.");
1661 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1664 while ($status = DBA::fetch($statuses)) {
1665 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1667 DBA::close($statuses);
1669 $data = ['status' => $ret];
1670 return DI::apiResponse()->formatData("statuses", $type, $data);
1673 api_register_func('api/conversation/show', 'api_conversation_show', true);
1674 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1679 * @param string $type Return type (atom, rss, xml, json)
1681 * @return array|string
1682 * @throws BadRequestException
1683 * @throws ForbiddenException
1684 * @throws ImagickException
1685 * @throws InternalServerErrorException
1686 * @throws UnauthorizedException
1687 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1689 function api_statuses_repeat($type)
1691 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1692 $uid = BaseApi::getCurrentUserID();
1695 $id = intval(DI::args()->getArgv()[3] ?? 0);
1698 $id = intval($_REQUEST['id'] ?? 0);
1703 $id = intval(DI::args()->getArgv()[4] ?? 0);
1706 logger::notice('API: api_statuses_repeat: ' . $id);
1708 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1709 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1711 if (DBA::isResult($item) && !empty($item['body'])) {
1712 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1713 if (!Item::performActivity($id, 'announce', $uid)) {
1714 throw new InternalServerErrorException();
1719 if (strpos($item['body'], "[/share]") !== false) {
1720 $pos = strpos($item['body'], "[share");
1721 $post = substr($item['body'], $pos);
1723 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1725 if (!empty($item['title'])) {
1726 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1729 $post .= $item['body'];
1730 $post .= "[/share]";
1732 $_REQUEST['body'] = $post;
1733 $_REQUEST['profile_uid'] = $uid;
1734 $_REQUEST['api_source'] = true;
1736 if (empty($_REQUEST['source'])) {
1737 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
1740 $item_id = item_post(DI::app());
1743 throw new ForbiddenException();
1746 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1748 // output the post that we just posted.
1749 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
1750 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
1753 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1756 * Destroys a specific status.
1758 * @param string $type Return type (atom, rss, xml, json)
1760 * @return array|string
1761 * @throws BadRequestException
1762 * @throws ForbiddenException
1763 * @throws ImagickException
1764 * @throws InternalServerErrorException
1765 * @throws UnauthorizedException
1766 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1768 function api_statuses_destroy($type)
1770 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1771 $uid = BaseApi::getCurrentUserID();
1774 $id = intval(DI::args()->getArgv()[3] ?? 0);
1777 $id = intval($_REQUEST['id'] ?? 0);
1782 $id = intval(DI::args()->getArgv()[4] ?? 0);
1785 logger::notice('API: api_statuses_destroy: ' . $id);
1787 $ret = api_statuses_show($type);
1789 Item::deleteForUser(['id' => $id], $uid);
1794 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1797 * Returns the most recent mentions.
1799 * @param string $type Return type (atom, rss, xml, json)
1801 * @return array|string
1802 * @throws BadRequestException
1803 * @throws ForbiddenException
1804 * @throws ImagickException
1805 * @throws InternalServerErrorException
1806 * @throws UnauthorizedException
1807 * @see http://developer.twitter.com/doc/get/statuses/mentions
1809 function api_statuses_mentions($type)
1811 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1812 $uid = BaseApi::getCurrentUserID();
1814 unset($_REQUEST['user_id']);
1815 unset($_GET['user_id']);
1817 unset($_REQUEST['screen_name']);
1818 unset($_GET['screen_name']);
1820 // get last network messages
1823 $since_id = intval($_REQUEST['since_id'] ?? 0);
1824 $max_id = intval($_REQUEST['max_id'] ?? 0);
1825 $count = intval($_REQUEST['count'] ?? 20);
1826 $page = intval($_REQUEST['page'] ?? 1);
1828 $start = max(0, ($page - 1) * $count);
1830 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1831 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1832 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1835 GRAVITY_PARENT, GRAVITY_COMMENT,
1837 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1838 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1839 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1844 $query .= " AND `id` <= ?";
1845 $condition[] = $max_id;
1848 array_unshift($condition, $query);
1850 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1851 $statuses = Post::selectForUser($uid, [], $condition, $params);
1853 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1856 while ($status = DBA::fetch($statuses)) {
1857 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1859 DBA::close($statuses);
1861 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1864 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1865 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1868 * Returns the most recent statuses posted by the user.
1870 * @param string $type Either "json" or "xml"
1871 * @return string|array
1872 * @throws BadRequestException
1873 * @throws ForbiddenException
1874 * @throws ImagickException
1875 * @throws InternalServerErrorException
1876 * @throws UnauthorizedException
1877 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1879 function api_statuses_user_timeline($type)
1881 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1882 $uid = BaseApi::getCurrentUserID();
1884 Logger::info('api_statuses_user_timeline', ['api_user' => $uid, '_REQUEST' => $_REQUEST]);
1886 $cid = BaseApi::getContactIDForSearchterm($_REQUEST['screen_name'] ?? '', $_REQUEST['user_id'] ?? 0, $uid);
1887 $since_id = $_REQUEST['since_id'] ?? 0;
1888 $max_id = $_REQUEST['max_id'] ?? 0;
1889 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1890 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1893 $count = $_REQUEST['count'] ?? 20;
1894 $page = $_REQUEST['page'] ?? 1;
1896 $start = max(0, ($page - 1) * $count);
1898 $condition = ["(`uid` = ? OR (`uid` = ? AND NOT `global`)) AND `gravity` IN (?, ?) AND `id` > ? AND `author-id` = ?",
1899 0, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $cid];
1901 if ($exclude_replies) {
1902 $condition[0] .= ' AND `gravity` = ?';
1903 $condition[] = GRAVITY_PARENT;
1906 if ($conversation_id > 0) {
1907 $condition[0] .= " AND `parent` = ?";
1908 $condition[] = $conversation_id;
1912 $condition[0] .= " AND `id` <= ?";
1913 $condition[] = $max_id;
1915 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1916 $statuses = Post::selectForUser($uid, [], $condition, $params);
1918 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1921 while ($status = DBA::fetch($statuses)) {
1922 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1924 DBA::close($statuses);
1926 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1929 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1932 * Star/unstar an item.
1933 * param: id : id of the item
1935 * @param string $type Return type (atom, rss, xml, json)
1937 * @return array|string
1938 * @throws BadRequestException
1939 * @throws ForbiddenException
1940 * @throws ImagickException
1941 * @throws InternalServerErrorException
1942 * @throws UnauthorizedException
1943 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1945 function api_favorites_create_destroy($type)
1947 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1948 $uid = BaseApi::getCurrentUserID();
1950 // for versioned api.
1951 /// @TODO We need a better global soluton
1952 $action_argv_id = 2;
1953 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1954 $action_argv_id = 3;
1957 if (DI::args()->getArgc() <= $action_argv_id) {
1958 throw new BadRequestException("Invalid request.");
1960 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1961 if (DI::args()->getArgc() == $action_argv_id + 2) {
1962 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1964 $itemid = intval($_REQUEST['id'] ?? 0);
1967 $item = Post::selectFirstForUser($uid, [], ['id' => $itemid, 'uid' => $uid]);
1969 if (!DBA::isResult($item)) {
1970 throw new BadRequestException("Invalid item.");
1975 $item['starred'] = 1;
1978 $item['starred'] = 0;
1981 throw new BadRequestException("Invalid action ".$action);
1984 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1987 throw new InternalServerErrorException("DB error");
1990 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1992 $ret = DI::twitterStatus()->createFromUriId($item['uri-id'], $item['uid'], $include_entities)->toArray();
1994 return DI::apiResponse()->formatData("status", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1997 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1998 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2001 * Returns the most recent favorite statuses.
2003 * @param string $type Return type (atom, rss, xml, json)
2005 * @return string|array
2006 * @throws BadRequestException
2007 * @throws ForbiddenException
2008 * @throws ImagickException
2009 * @throws InternalServerErrorException
2010 * @throws UnauthorizedException
2012 function api_favorites($type)
2014 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2015 $uid = BaseApi::getCurrentUserID();
2017 // in friendica starred item are private
2018 // return favorites only for self
2019 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites']);
2022 $since_id = $_REQUEST['since_id'] ?? 0;
2023 $max_id = $_REQUEST['max_id'] ?? 0;
2024 $count = $_GET['count'] ?? 20;
2025 $page = $_REQUEST['page'] ?? 1;
2027 $start = max(0, ($page - 1) * $count);
2029 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2030 $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2032 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2035 $condition[0] .= " AND `id` <= ?";
2036 $condition[] = $max_id;
2039 $statuses = Post::selectForUser($uid, [], $condition, $params);
2041 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
2044 while ($status = DBA::fetch($statuses)) {
2045 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
2047 DBA::close($statuses);
2049 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
2052 api_register_func('api/favorites', 'api_favorites', true);
2055 * Returns all lists the user subscribes to.
2057 * @param string $type Return type (atom, rss, xml, json)
2059 * @return array|string
2060 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2062 function api_lists_list($type)
2065 /// @TODO $ret is not filled here?
2066 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2069 api_register_func('api/lists/list', 'api_lists_list', true);
2070 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2073 * Returns all groups the user owns.
2075 * @param string $type Return type (atom, rss, xml, json)
2077 * @return array|string
2078 * @throws BadRequestException
2079 * @throws ForbiddenException
2080 * @throws ImagickException
2081 * @throws InternalServerErrorException
2082 * @throws UnauthorizedException
2083 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2085 function api_lists_ownerships($type)
2087 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2088 $uid = BaseApi::getCurrentUserID();
2091 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
2093 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2095 // loop through all groups
2097 foreach ($groups as $group) {
2098 if ($group['visible']) {
2104 'name' => $group['name'],
2105 'id' => intval($group['id']),
2106 'id_str' => (string) $group['id'],
2107 'user' => $user_info,
2111 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2114 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2117 * Returns recent statuses from users in the specified group.
2119 * @param string $type Return type (atom, rss, xml, json)
2121 * @return array|string
2122 * @throws BadRequestException
2123 * @throws ForbiddenException
2124 * @throws ImagickException
2125 * @throws InternalServerErrorException
2126 * @throws UnauthorizedException
2127 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2129 function api_lists_statuses($type)
2131 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2132 $uid = BaseApi::getCurrentUserID();
2134 unset($_REQUEST['user_id']);
2135 unset($_GET['user_id']);
2137 unset($_REQUEST['screen_name']);
2138 unset($_GET['screen_name']);
2140 if (empty($_REQUEST['list_id'])) {
2141 throw new BadRequestException('list_id not specified');
2145 $count = $_REQUEST['count'] ?? 20;
2146 $page = $_REQUEST['page'] ?? 1;
2147 $since_id = $_REQUEST['since_id'] ?? 0;
2148 $max_id = $_REQUEST['max_id'] ?? 0;
2149 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2150 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2152 $start = max(0, ($page - 1) * $count);
2154 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2155 $gids = array_column($groups, 'contact-id');
2156 $condition = ['uid' => $uid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2157 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2160 $condition[0] .= " AND `id` <= ?";
2161 $condition[] = $max_id;
2163 if ($exclude_replies > 0) {
2164 $condition[0] .= ' AND `gravity` = ?';
2165 $condition[] = GRAVITY_PARENT;
2167 if ($conversation_id > 0) {
2168 $condition[0] .= " AND `parent` = ?";
2169 $condition[] = $conversation_id;
2172 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2173 $statuses = Post::selectForUser($uid, [], $condition, $params);
2175 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
2178 while ($status = DBA::fetch($statuses)) {
2179 $items[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
2181 DBA::close($statuses);
2183 return DI::apiResponse()->formatData("statuses", $type, ['status' => $items], Contact::getPublicIdByUserId($uid));
2186 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2189 * Returns either the friends of the follower list
2191 * Considers friends and followers lists to be private and won't return
2192 * anything if any user_id parameter is passed.
2194 * @param string $qtype Either "friends" or "followers"
2195 * @return boolean|array
2196 * @throws BadRequestException
2197 * @throws ForbiddenException
2198 * @throws ImagickException
2199 * @throws InternalServerErrorException
2200 * @throws UnauthorizedException
2202 function api_statuses_f($qtype)
2204 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2205 $uid = BaseApi::getCurrentUserID();
2208 $count = $_GET['count'] ?? 20;
2209 $page = $_GET['page'] ?? 1;
2211 $start = max(0, ($page - 1) * $count);
2213 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2214 /* this is to stop Hotot to load friends multiple times
2215 * I'm not sure if I'm missing return something or
2216 * is a bug in hotot. Workaround, meantime
2220 return array('$users' => $ret);*/
2225 if ($qtype == 'friends') {
2226 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2227 } elseif ($qtype == 'followers') {
2228 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2231 if ($qtype == 'blocks') {
2232 $sql_filter = 'AND `blocked` AND NOT `pending`';
2233 } elseif ($qtype == 'incoming') {
2234 $sql_filter = 'AND `pending`';
2236 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2239 // @todo This query most likely can be replaced with a Contact::select...
2240 $r = DBA::toArray(DBA::p(
2255 foreach ($r as $cid) {
2256 $user = DI::twitterUser()->createFromContactId($cid['id'], $uid)->toArray();
2257 // "uid" is only needed for some internal stuff, so remove it from here
2258 unset($user['uid']);
2265 return ['user' => $ret];
2269 * Returns the list of friends of the provided user
2271 * @deprecated By Twitter API in favor of friends/list
2273 * @param string $type Either "json" or "xml"
2274 * @return boolean|string|array
2275 * @throws BadRequestException
2276 * @throws ForbiddenException
2278 function api_statuses_friends($type)
2280 $data = api_statuses_f("friends");
2281 if ($data === false) {
2284 return DI::apiResponse()->formatData("users", $type, $data);
2287 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2290 * Returns the list of followers of the provided user
2292 * @deprecated By Twitter API in favor of friends/list
2294 * @param string $type Either "json" or "xml"
2295 * @return boolean|string|array
2296 * @throws BadRequestException
2297 * @throws ForbiddenException
2299 function api_statuses_followers($type)
2301 $data = api_statuses_f("followers");
2302 if ($data === false) {
2305 return DI::apiResponse()->formatData("users", $type, $data);
2308 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2311 * Returns the list of blocked users
2313 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
2315 * @param string $type Either "json" or "xml"
2317 * @return boolean|string|array
2318 * @throws BadRequestException
2319 * @throws ForbiddenException
2321 function api_blocks_list($type)
2323 $data = api_statuses_f('blocks');
2324 if ($data === false) {
2327 return DI::apiResponse()->formatData("users", $type, $data);
2330 api_register_func('api/blocks/list', 'api_blocks_list', true);
2333 * Returns the list of pending users IDs
2335 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
2337 * @param string $type Either "json" or "xml"
2339 * @return boolean|string|array
2340 * @throws BadRequestException
2341 * @throws ForbiddenException
2343 function api_friendships_incoming($type)
2345 $data = api_statuses_f('incoming');
2346 if ($data === false) {
2351 foreach ($data['user'] as $user) {
2352 $ids[] = $user['id'];
2355 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
2358 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
2361 * Sends a new direct message.
2363 * @param string $type Return type (atom, rss, xml, json)
2365 * @return array|string
2366 * @throws BadRequestException
2367 * @throws ForbiddenException
2368 * @throws ImagickException
2369 * @throws InternalServerErrorException
2370 * @throws NotFoundException
2371 * @throws UnauthorizedException
2372 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
2374 function api_direct_messages_new($type)
2376 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2377 $uid = BaseApi::getCurrentUserID();
2379 if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
2383 $sender = DI::twitterUser()->createFromUserId($uid)->toArray();
2385 $cid = BaseApi::getContactIDForSearchterm($_POST['screen_name'] ?? '', $_POST['user_id'] ?? 0, $uid);
2387 throw new NotFoundException('Recipient not found');
2391 if (!empty($_REQUEST['replyto'])) {
2392 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
2393 $replyto = $mail['parent-uri'];
2394 $sub = $mail['title'];
2396 if (!empty($_REQUEST['title'])) {
2397 $sub = $_REQUEST['title'];
2399 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
2403 $cdata = Contact::getPublicAndUserContactID($cid, $uid);
2405 $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
2408 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
2409 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid)->toArray(), $sender);
2411 $ret = ["error" => $id];
2414 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2417 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
2420 * delete a direct_message from mail table through api
2422 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2423 * @return string|array
2424 * @throws BadRequestException
2425 * @throws ForbiddenException
2426 * @throws ImagickException
2427 * @throws InternalServerErrorException
2428 * @throws UnauthorizedException
2429 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
2431 function api_direct_messages_destroy($type)
2433 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2434 $uid = BaseApi::getCurrentUserID();
2437 $id = $_REQUEST['id'] ?? 0;
2439 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
2440 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
2441 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
2443 // error if no id or parenturi specified (for clients posting parent-uri as well)
2444 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
2445 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
2446 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2449 // BadRequestException if no id specified (for clients using Twitter API)
2451 throw new BadRequestException('Message id not specified');
2454 // add parent-uri to sql command if specified by calling app
2455 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
2457 // error message if specified id is not in database
2458 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
2459 if ($verbose == "true") {
2460 $answer = ['result' => 'error', 'message' => 'message id not in database'];
2461 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2463 /// @todo BadRequestException ok for Twitter API clients?
2464 throw new BadRequestException('message id not in database');
2468 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
2470 if ($verbose == "true") {
2473 $answer = ['result' => 'ok', 'message' => 'message deleted'];
2474 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
2476 $answer = ['result' => 'error', 'message' => 'unknown error'];
2477 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2480 /// @todo return JSON data like Twitter API not yet implemented
2483 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2488 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2489 * @return string|array
2490 * @throws HTTPException\BadRequestException
2491 * @throws HTTPException\ExpectationFailedException
2492 * @throws HTTPException\ForbiddenException
2493 * @throws HTTPException\InternalServerErrorException
2494 * @throws HTTPException\NotFoundException
2495 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
2497 function api_friendships_destroy($type)
2499 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2500 $uid = BaseApi::getCurrentUserID();
2502 $owner = User::getOwnerDataById($uid);
2504 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
2505 throw new HTTPException\NotFoundException('Error Processing Request');
2508 $contact_id = $_REQUEST['user_id'] ?? 0;
2510 if (empty($contact_id)) {
2511 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
2512 throw new HTTPException\BadRequestException('no user_id specified');
2515 // Get Contact by given id
2516 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
2518 if(!DBA::isResult($contact)) {
2519 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
2520 throw new HTTPException\NotFoundException('no contact found to given ID');
2523 $url = $contact['url'];
2525 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
2526 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
2527 Strings::normaliseLink($url), $url];
2528 $contact = DBA::selectFirst('contact', [], $condition);
2530 if (!DBA::isResult($contact)) {
2531 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
2532 throw new HTTPException\NotFoundException('Not following Contact');
2536 $result = Contact::terminateFriendship($owner, $contact);
2538 if ($result === null) {
2539 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
2540 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
2543 if ($result === false) {
2544 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
2546 } catch (Exception $e) {
2547 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
2548 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
2551 // "uid" is only needed for some internal stuff, so remove it from here
2552 unset($contact['uid']);
2554 // Set screen_name since Twidere requests it
2555 $contact['screen_name'] = $contact['nick'];
2557 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
2560 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
2564 * @param string $type Return type (atom, rss, xml, json)
2565 * @param string $box
2566 * @param string $verbose
2568 * @return array|string
2569 * @throws BadRequestException
2570 * @throws ForbiddenException
2571 * @throws ImagickException
2572 * @throws InternalServerErrorException
2573 * @throws UnauthorizedException
2575 function api_direct_messages_box($type, $box, $verbose)
2577 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2578 $uid = BaseApi::getCurrentUserID();
2581 $count = $_GET['count'] ?? 20;
2582 $page = $_REQUEST['page'] ?? 1;
2584 $since_id = $_REQUEST['since_id'] ?? 0;
2585 $max_id = $_REQUEST['max_id'] ?? 0;
2587 $user_id = $_REQUEST['user_id'] ?? '';
2588 $screen_name = $_REQUEST['screen_name'] ?? '';
2591 unset($_REQUEST['user_id']);
2592 unset($_GET['user_id']);
2594 unset($_REQUEST['screen_name']);
2595 unset($_GET['screen_name']);
2597 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
2599 $profile_url = $user_info["url"];
2602 $start = max(0, ($page - 1) * $count);
2607 if ($box=="sentbox") {
2608 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
2609 } elseif ($box == "conversation") {
2610 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
2611 } elseif ($box == "all") {
2612 $sql_extra = "true";
2613 } elseif ($box == "inbox") {
2614 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
2618 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
2621 if ($user_id != "") {
2622 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2623 } elseif ($screen_name !="") {
2624 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
2627 $r = DBA::toArray(DBA::p(
2628 "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 ?,?",
2634 if ($verbose == "true" && !DBA::isResult($r)) {
2635 $answer = ['result' => 'error', 'message' => 'no mails available'];
2636 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
2640 foreach ($r as $item) {
2641 if ($box == "inbox" || $item['from-url'] != $profile_url) {
2642 $recipient = $user_info;
2643 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
2644 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
2645 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
2646 $sender = $user_info;
2649 if (isset($recipient) && isset($sender)) {
2650 $ret[] = api_format_messages($item, $recipient, $sender);
2654 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2658 * Returns the most recent direct messages sent by the user.
2660 * @param string $type Return type (atom, rss, xml, json)
2662 * @return array|string
2663 * @throws BadRequestException
2664 * @throws ForbiddenException
2665 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
2667 function api_direct_messages_sentbox($type)
2669 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2670 return api_direct_messages_box($type, "sentbox", $verbose);
2673 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
2676 * Returns the most recent direct messages sent to the user.
2678 * @param string $type Return type (atom, rss, xml, json)
2680 * @return array|string
2681 * @throws BadRequestException
2682 * @throws ForbiddenException
2683 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
2685 function api_direct_messages_inbox($type)
2687 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2688 return api_direct_messages_box($type, "inbox", $verbose);
2691 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
2695 * @param string $type Return type (atom, rss, xml, json)
2697 * @return array|string
2698 * @throws BadRequestException
2699 * @throws ForbiddenException
2701 function api_direct_messages_all($type)
2703 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2704 return api_direct_messages_box($type, "all", $verbose);
2707 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
2711 * @param string $type Return type (atom, rss, xml, json)
2713 * @return array|string
2714 * @throws BadRequestException
2715 * @throws ForbiddenException
2717 function api_direct_messages_conversation($type)
2719 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2720 return api_direct_messages_box($type, "conversation", $verbose);
2723 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
2726 * list all photos of the authenticated user
2728 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2729 * @return string|array
2730 * @throws ForbiddenException
2731 * @throws InternalServerErrorException
2733 function api_fr_photos_list($type)
2735 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2736 $uid = BaseApi::getCurrentUserID();
2738 $r = DBA::toArray(DBA::p(
2739 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
2740 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
2741 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
2742 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
2745 'image/jpeg' => 'jpg',
2746 'image/png' => 'png',
2747 'image/gif' => 'gif'
2749 $data = ['photo'=>[]];
2750 if (DBA::isResult($r)) {
2751 foreach ($r as $rr) {
2753 $photo['id'] = $rr['resource-id'];
2754 $photo['album'] = $rr['album'];
2755 $photo['filename'] = $rr['filename'];
2756 $photo['type'] = $rr['type'];
2757 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
2758 $photo['created'] = $rr['created'];
2759 $photo['edited'] = $rr['edited'];
2760 $photo['desc'] = $rr['desc'];
2762 if ($type == "xml") {
2763 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
2765 $photo['thumb'] = $thumb;
2766 $data['photo'][] = $photo;
2770 return DI::apiResponse()->formatData("photos", $type, $data);
2773 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2776 * upload a new photo or change an existing photo
2778 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2779 * @return string|array
2780 * @throws BadRequestException
2781 * @throws ForbiddenException
2782 * @throws ImagickException
2783 * @throws InternalServerErrorException
2784 * @throws NotFoundException
2786 function api_fr_photo_create_update($type)
2788 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2789 $uid = BaseApi::getCurrentUserID();
2792 $photo_id = $_REQUEST['photo_id'] ?? null;
2793 $desc = $_REQUEST['desc'] ?? null;
2794 $album = $_REQUEST['album'] ?? null;
2795 $album_new = $_REQUEST['album_new'] ?? null;
2796 $allow_cid = $_REQUEST['allow_cid'] ?? null;
2797 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
2798 $allow_gid = $_REQUEST['allow_gid'] ?? null;
2799 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
2800 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
2802 // do several checks on input parameters
2803 // we do not allow calls without album string
2804 if ($album == null) {
2805 throw new BadRequestException("no albumname specified");
2807 // if photo_id == null --> we are uploading a new photo
2808 if ($photo_id == null) {
2811 // error if no media posted in create-mode
2812 if (empty($_FILES['media'])) {
2814 throw new BadRequestException("no media data submitted");
2817 // album_new will be ignored in create-mode
2822 // check if photo is existing in databasei
2823 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
2824 throw new BadRequestException("photo not available");
2828 // checks on acl strings provided by clients
2829 $acl_input_error = false;
2830 $acl_input_error |= check_acl_input($allow_cid, $uid);
2831 $acl_input_error |= check_acl_input($deny_cid, $uid);
2832 $acl_input_error |= check_acl_input($allow_gid, $uid);
2833 $acl_input_error |= check_acl_input($deny_gid, $uid);
2834 if ($acl_input_error) {
2835 throw new BadRequestException("acl data invalid");
2837 // now let's upload the new media in create-mode
2838 if ($mode == "create") {
2839 $media = $_FILES['media'];
2840 $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);
2842 // return success of updating or error message
2843 if (!is_null($data)) {
2844 return DI::apiResponse()->formatData("photo_create", $type, $data);
2846 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
2850 // now let's do the changes in update-mode
2851 if ($mode == "update") {
2852 $updated_fields = [];
2854 if (!is_null($desc)) {
2855 $updated_fields['desc'] = $desc;
2858 if (!is_null($album_new)) {
2859 $updated_fields['album'] = $album_new;
2862 if (!is_null($allow_cid)) {
2863 $allow_cid = trim($allow_cid);
2864 $updated_fields['allow_cid'] = $allow_cid;
2867 if (!is_null($deny_cid)) {
2868 $deny_cid = trim($deny_cid);
2869 $updated_fields['deny_cid'] = $deny_cid;
2872 if (!is_null($allow_gid)) {
2873 $allow_gid = trim($allow_gid);
2874 $updated_fields['allow_gid'] = $allow_gid;
2877 if (!is_null($deny_gid)) {
2878 $deny_gid = trim($deny_gid);
2879 $updated_fields['deny_gid'] = $deny_gid;
2883 if (count($updated_fields) > 0) {
2884 $nothingtodo = false;
2885 $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
2887 $nothingtodo = true;
2890 if (!empty($_FILES['media'])) {
2891 $nothingtodo = false;
2892 $media = $_FILES['media'];
2893 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
2894 if (!is_null($data)) {
2895 return DI::apiResponse()->formatData("photo_update", $type, $data);
2899 // return success of updating or error message
2901 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
2902 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
2905 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
2906 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
2908 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
2911 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
2914 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
2915 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
2918 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
2920 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2921 * @return string|array
2922 * @throws BadRequestException
2923 * @throws ForbiddenException
2924 * @throws InternalServerErrorException
2925 * @throws NotFoundException
2927 function api_fr_photo_detail($type)
2929 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2930 $uid = BaseApi::getCurrentUserID();
2932 if (empty($_REQUEST['photo_id'])) {
2933 throw new BadRequestException("No photo id.");
2936 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
2937 $photo_id = $_REQUEST['photo_id'];
2939 // prepare json/xml output with data from database for the requested photo
2940 $data = prepare_photo_data($type, $scale, $photo_id, $uid);
2942 return DI::apiResponse()->formatData("photo_detail", $type, $data);
2945 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2948 * updates the profile image for the user (either a specified profile or the default profile)
2950 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2952 * @return string|array
2953 * @throws BadRequestException
2954 * @throws ForbiddenException
2955 * @throws ImagickException
2956 * @throws InternalServerErrorException
2957 * @throws NotFoundException
2958 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
2960 function api_account_update_profile_image($type)
2962 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2963 $uid = BaseApi::getCurrentUserID();
2966 $profile_id = $_REQUEST['profile_id'] ?? 0;
2968 // error if image data is missing
2969 if (empty($_FILES['image'])) {
2970 throw new BadRequestException("no media data submitted");
2973 // check if specified profile id is valid
2974 if ($profile_id != 0) {
2975 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
2976 // error message if specified profile id is not in database
2977 if (!DBA::isResult($profile)) {
2978 throw new BadRequestException("profile_id not available");
2980 $is_default_profile = $profile['is-default'];
2982 $is_default_profile = 1;
2985 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
2987 if (!empty($_FILES['image'])) {
2988 $media = $_FILES['image'];
2989 } elseif (!empty($_FILES['media'])) {
2990 $media = $_FILES['media'];
2992 // save new profile image
2993 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
2996 if (is_array($media['type'])) {
2997 $filetype = $media['type'][0];
2999 $filetype = $media['type'];
3001 if ($filetype == "image/jpeg") {
3003 } elseif ($filetype == "image/png") {
3006 throw new InternalServerErrorException('Unsupported filetype');
3009 // change specified profile or all profiles to the new resource-id
3010 if ($is_default_profile) {
3011 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
3012 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3014 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3015 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3016 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
3019 Contact::updateSelfFromUserID($uid, true);
3021 // Update global directory in background
3022 Profile::publishUpdate($uid);
3024 // output for client
3026 return api_account_verify_credentials($type);
3028 // SaveMediaToDatabase failed for some reason
3029 throw new InternalServerErrorException("image upload failed");
3033 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3036 * Update user profile
3038 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3040 * @return array|string
3041 * @throws BadRequestException
3042 * @throws ForbiddenException
3043 * @throws ImagickException
3044 * @throws InternalServerErrorException
3045 * @throws UnauthorizedException
3047 function api_account_update_profile($type)
3049 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3050 $uid = BaseApi::getCurrentUserID();
3052 $api_user = DI::twitterUser()->createFromUserId($uid)->toArray();
3054 if (!empty($_POST['name'])) {
3055 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $uid]);
3056 DBA::update('user', ['username' => $_POST['name']], ['uid' => $uid]);
3057 Contact::update(['name' => $_POST['name']], ['uid' => $uid, 'self' => 1]);
3058 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3061 if (isset($_POST['description'])) {
3062 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $uid]);
3063 Contact::update(['about' => $_POST['description']], ['uid' => $uid, 'self' => 1]);
3064 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3067 Profile::publishUpdate($uid);
3069 return api_account_verify_credentials($type);
3072 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3075 * Return all or a specified group of the user with the containing contacts.
3077 * @param string $type Return type (atom, rss, xml, json)
3079 * @return array|string
3080 * @throws BadRequestException
3081 * @throws ForbiddenException
3082 * @throws ImagickException
3083 * @throws InternalServerErrorException
3084 * @throws UnauthorizedException
3086 function api_friendica_group_show($type)
3088 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3089 $uid = BaseApi::getCurrentUserID();
3092 $gid = $_REQUEST['gid'] ?? 0;
3094 // get data of the specified group id or all groups if not specified
3096 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
3098 // error message if specified gid is not in database
3099 if (!DBA::isResult($groups)) {
3100 throw new BadRequestException("gid not available");
3103 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
3106 // loop through all groups and retrieve all members for adding data in the user array
3108 foreach ($groups as $rr) {
3109 $members = Contact\Group::getById($rr['id']);
3112 if ($type == "xml") {
3113 $user_element = "users";
3115 foreach ($members as $member) {
3116 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid)->toArray();
3117 $users[$k++.":user"] = $user;
3120 $user_element = "user";
3121 foreach ($members as $member) {
3122 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid)->toArray();
3126 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
3128 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
3131 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3136 * @param string $type Return type (atom, rss, xml, json)
3138 * @return array|string
3139 * @throws BadRequestException
3140 * @throws ForbiddenException
3141 * @throws ImagickException
3142 * @throws InternalServerErrorException
3143 * @throws UnauthorizedException
3144 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
3146 function api_lists_destroy($type)
3148 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3149 $uid = BaseApi::getCurrentUserID();
3152 $gid = $_REQUEST['list_id'] ?? 0;
3154 // error if no gid specified
3156 throw new BadRequestException('gid not specified');
3159 // get data of the specified group id
3160 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
3161 // error message if specified gid is not in database
3163 throw new BadRequestException('gid not available');
3166 if (Group::remove($gid)) {
3168 'name' => $group['name'],
3169 'id' => intval($gid),
3170 'id_str' => (string) $gid,
3171 'user' => DI::twitterUser()->createFromUserId($uid)->toArray()
3174 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
3178 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
3181 * Create the specified group with the posted array of contacts.
3183 * @param string $type Return type (atom, rss, xml, json)
3185 * @return array|string
3186 * @throws BadRequestException
3187 * @throws ForbiddenException
3188 * @throws ImagickException
3189 * @throws InternalServerErrorException
3190 * @throws UnauthorizedException
3192 function api_friendica_group_create($type)
3194 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3195 $uid = BaseApi::getCurrentUserID();
3198 $name = $_REQUEST['name'] ?? '';
3199 $json = json_decode($_POST['json'], true);
3200 $users = $json['user'];
3202 $success = group_create($name, $uid, $users);
3204 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
3207 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3210 * Create a new group.
3212 * @param string $type Return type (atom, rss, xml, json)
3214 * @return array|string
3215 * @throws BadRequestException
3216 * @throws ForbiddenException
3217 * @throws ImagickException
3218 * @throws InternalServerErrorException
3219 * @throws UnauthorizedException
3220 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
3222 function api_lists_create($type)
3224 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3225 $uid = BaseApi::getCurrentUserID();
3228 $name = $_REQUEST['name'] ?? '';
3230 $success = group_create($name, $uid);
3231 if ($success['success']) {
3233 'name' => $success['name'],
3234 'id' => intval($success['gid']),
3235 'id_str' => (string) $success['gid'],
3236 'user' => DI::twitterUser()->createFromUserId($uid)->toArray()
3239 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
3243 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
3246 * Update the specified group with the posted array of contacts.
3248 * @param string $type Return type (atom, rss, xml, json)
3250 * @return array|string
3251 * @throws BadRequestException
3252 * @throws ForbiddenException
3253 * @throws ImagickException
3254 * @throws InternalServerErrorException
3255 * @throws UnauthorizedException
3257 function api_friendica_group_update($type)
3259 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3260 $uid = BaseApi::getCurrentUserID();
3263 $gid = $_REQUEST['gid'] ?? 0;
3264 $name = $_REQUEST['name'] ?? '';
3265 $json = json_decode($_POST['json'], true);
3266 $users = $json['user'];
3268 // error if no name specified
3270 throw new BadRequestException('group name not specified');
3273 // error if no gid specified
3275 throw new BadRequestException('gid not specified');
3279 $members = Contact\Group::getById($gid);
3280 foreach ($members as $member) {
3281 $cid = $member['id'];
3282 foreach ($users as $user) {
3283 $found = ($user['cid'] == $cid ? true : false);
3285 if (!isset($found) || !$found) {
3286 $gid = Group::getIdByName($uid, $name);
3287 Group::removeMember($gid, $cid);
3292 $erroraddinguser = false;
3294 foreach ($users as $user) {
3295 $cid = $user['cid'];
3297 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
3298 Group::addMember($gid, $cid);
3300 $erroraddinguser = true;
3301 $errorusers[] = $cid;
3305 // return success message incl. missing users in array
3306 $status = ($erroraddinguser ? "missing user" : "ok");
3307 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
3308 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
3311 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3314 * Update information about a group.
3316 * @param string $type Return type (atom, rss, xml, json)
3318 * @return array|string
3319 * @throws BadRequestException
3320 * @throws ForbiddenException
3321 * @throws ImagickException
3322 * @throws InternalServerErrorException
3323 * @throws UnauthorizedException
3324 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
3326 function api_lists_update($type)
3328 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3329 $uid = BaseApi::getCurrentUserID();
3332 $gid = $_REQUEST['list_id'] ?? 0;
3333 $name = $_REQUEST['name'] ?? '';
3335 // error if no gid specified
3337 throw new BadRequestException('gid not specified');
3340 // get data of the specified group id
3341 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
3342 // error message if specified gid is not in database
3344 throw new BadRequestException('gid not available');
3347 if (Group::update($gid, $name)) {
3350 'id' => intval($gid),
3351 'id_str' => (string) $gid,
3352 'user' => DI::twitterUser()->createFromUserId($uid)->toArray()
3355 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
3359 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
3362 * Set notification as seen and returns associated item (if possible)
3364 * POST request with 'id' param as notification id
3366 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3367 * @return string|array
3368 * @throws BadRequestException
3369 * @throws ForbiddenException
3370 * @throws ImagickException
3371 * @throws InternalServerErrorException
3372 * @throws UnauthorizedException
3374 function api_friendica_notification_seen($type)
3376 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3377 $uid = BaseApi::getCurrentUserID();
3379 if (DI::args()->getArgc() !== 4) {
3380 throw new BadRequestException('Invalid argument count');
3383 $id = intval($_REQUEST['id'] ?? 0);
3386 $Notify = DI::notify()->selectOneById($id);
3387 if ($Notify->uid !== $uid) {
3388 throw new NotFoundException();
3391 if ($Notify->uriId) {
3392 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
3396 DI::notify()->save($Notify);
3398 if ($Notify->otype === Notification\ObjectType::ITEM) {
3399 $item = Post::selectFirstForUser($uid, [], ['id' => $Notify->iid, 'uid' => $uid]);
3400 if (DBA::isResult($item)) {
3401 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
3403 // we found the item, return it to the user
3404 $ret = [DI::twitterStatus()->createFromUriId($item['uri-id'], $item['uid'], $include_entities)->toArray()];
3405 $data = ['status' => $ret];
3406 return DI::apiResponse()->formatData('status', $type, $data);
3408 // the item can't be found, but we set the notification as seen, so we count this as a success
3411 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
3412 } catch (NotFoundException $e) {
3413 throw new BadRequestException('Invalid argument', $e);
3414 } catch (Exception $e) {
3415 throw new InternalServerErrorException('Internal Server exception', $e);
3419 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3422 * search for direct_messages containing a searchstring through api
3424 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3425 * @param string $box
3426 * @return string|array (success: success=true if found and search_result contains found messages,
3427 * success=false if nothing was found, search_result='nothing found',
3428 * error: result=error with error message)
3429 * @throws BadRequestException
3430 * @throws ForbiddenException
3431 * @throws ImagickException
3432 * @throws InternalServerErrorException
3433 * @throws UnauthorizedException
3435 function api_friendica_direct_messages_search($type, $box = "")
3437 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3438 $uid = BaseApi::getCurrentUserID();
3441 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
3442 $searchstring = $_REQUEST['searchstring'] ?? '';
3444 // error if no searchstring specified
3445 if ($searchstring == "") {
3446 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
3447 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
3450 // get data for the specified searchstring
3451 $r = DBA::toArray(DBA::p(
3452 "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",
3454 '%'.$searchstring.'%'
3457 $profile_url = $user_info["url"];
3459 // message if nothing was found
3460 if (!DBA::isResult($r)) {
3461 $success = ['success' => false, 'search_results' => 'problem with query'];
3462 } elseif (count($r) == 0) {
3463 $success = ['success' => false, 'search_results' => 'nothing found'];
3466 foreach ($r as $item) {
3467 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3468 $recipient = $user_info;
3469 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
3470 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3471 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
3472 $sender = $user_info;
3475 if (isset($recipient) && isset($sender)) {
3476 $ret[] = api_format_messages($item, $recipient, $sender);
3479 $success = ['success' => true, 'search_results' => $ret];
3482 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
3485 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);