3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\System;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Group;
36 use Friendica\Model\Item;
37 use Friendica\Model\Mail;
38 use Friendica\Model\Notification;
39 use Friendica\Model\Photo;
40 use Friendica\Model\Post;
41 use Friendica\Model\Profile;
42 use Friendica\Model\User;
43 use Friendica\Module\BaseApi;
44 use Friendica\Network\HTTPException;
45 use Friendica\Network\HTTPException\BadRequestException;
46 use Friendica\Network\HTTPException\ForbiddenException;
47 use Friendica\Network\HTTPException\InternalServerErrorException;
48 use Friendica\Network\HTTPException\NotFoundException;
49 use Friendica\Network\HTTPException\TooManyRequestsException;
50 use Friendica\Network\HTTPException\UnauthorizedException;
51 use Friendica\Object\Image;
52 use Friendica\Security\BasicAuth;
53 use Friendica\Util\DateTimeFormat;
54 use Friendica\Util\Images;
55 use Friendica\Util\Network;
56 use Friendica\Util\Strings;
58 require_once __DIR__ . '/../mod/item.php';
59 require_once __DIR__ . '/../mod/wall_upload.php';
61 define('API_METHOD_ANY', '*');
62 define('API_METHOD_GET', 'GET');
63 define('API_METHOD_POST', 'POST,PUT');
64 define('API_METHOD_DELETE', 'POST,DELETE');
66 define('API_LOG_PREFIX', 'API {action} - ');
71 * Register a function to be the endpoint for defined API path.
73 * @param string $path API URL path, relative to DI::baseUrl()
74 * @param string $func Function name to call on path request
75 * @param bool $auth API need logged user
76 * @param string $method HTTP method reqiured to call this endpoint.
77 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
78 * Default to API_METHOD_ANY
80 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
90 // Workaround for hotot
91 $path = str_replace("api/", "api/1.1/", $path);
101 * Main API entry point
103 * Authenticate user, call registered API function, set HTTP headers
106 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
107 * @return string|array API call result
110 function api_call(App $a, App\Arguments $args = null)
119 if (strpos($args->getCommand(), ".xml") > 0) {
122 if (strpos($args->getCommand(), ".json") > 0) {
125 if (strpos($args->getCommand(), ".rss") > 0) {
128 if (strpos($args->getCommand(), ".atom") > 0) {
133 foreach ($API as $p => $info) {
134 if (strpos($args->getCommand(), $p) === 0) {
135 if (!empty($info['auth']) && BaseApi::getCurrentUserID() === false) {
136 BasicAuth::getCurrentUserID(true);
137 Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
140 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
142 $stamp = microtime(true);
143 $return = call_user_func($info['func'], $type);
144 $duration = floatval(microtime(true) - $stamp);
146 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
148 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
150 if (false === $return) {
152 * api function returned false withour throw an
153 * exception. This should not happend, throw a 500
155 throw new InternalServerErrorException();
160 header("Content-Type: text/xml");
163 header("Content-Type: application/json");
164 if (!empty($return)) {
165 $json = json_encode(end($return));
166 if (!empty($_GET['callback'])) {
167 $json = $_GET['callback'] . "(" . $json . ")";
173 header("Content-Type: application/rss+xml");
174 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
177 header("Content-Type: application/atom+xml");
178 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
185 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
186 throw new NotFoundException();
187 } catch (HTTPException $e) {
188 Logger::notice(API_LOG_PREFIX . 'got exception', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString(), 'error' => $e]);
189 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
196 * @param array $recipient
197 * @param array $sender
200 * @throws InternalServerErrorException
202 function api_format_messages($item, $recipient, $sender)
204 // standard meta information
207 'sender_id' => $sender['id'],
209 'recipient_id' => $recipient['id'],
210 'created_at' => DateTimeFormat::utc($item['created'] ?? 'now', DateTimeFormat::API),
211 'sender_screen_name' => $sender['screen_name'],
212 'recipient_screen_name' => $recipient['screen_name'],
214 'recipient' => $recipient,
216 'friendica_seen' => $item['seen'] ?? 0,
217 'friendica_parent_uri' => $item['parent-uri'] ?? '',
220 // "uid" is only needed for some internal stuff, so remove it from here
221 if (isset($ret['sender']['uid'])) {
222 unset($ret['sender']['uid']);
224 if (isset($ret['recipient']['uid'])) {
225 unset($ret['recipient']['uid']);
228 //don't send title to regular StatusNET requests to avoid confusing these apps
229 if (!empty($_GET['getText'])) {
230 $ret['title'] = $item['title'];
231 if ($_GET['getText'] == 'html') {
232 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
233 } elseif ($_GET['getText'] == 'plain') {
234 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
237 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
239 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
240 unset($ret['sender']);
241 unset($ret['recipient']);
249 * @param string $acl_string
254 function check_acl_input($acl_string, $uid)
256 if (empty($acl_string)) {
260 $contact_not_found = false;
262 // split <x><y><z> into array of cid's
263 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
265 // check for each cid if it is available on server
266 $cid_array = $array[0];
267 foreach ($cid_array as $cid) {
268 $cid = str_replace("<", "", $cid);
269 $cid = str_replace(">", "", $cid);
270 $condition = ['id' => $cid, 'uid' => $uid];
271 $contact_not_found |= !DBA::exists('contact', $condition);
273 return $contact_not_found;
277 * @param string $mediatype
278 * @param array $media
279 * @param string $type
280 * @param string $album
281 * @param string $allow_cid
282 * @param string $deny_cid
283 * @param string $allow_gid
284 * @param string $deny_gid
285 * @param string $desc
286 * @param integer $phototype
287 * @param boolean $visibility
288 * @param string $photo_id
291 * @throws BadRequestException
292 * @throws ForbiddenException
293 * @throws ImagickException
294 * @throws InternalServerErrorException
295 * @throws NotFoundException
296 * @throws UnauthorizedException
298 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype, $visibility, $photo_id, $uid)
306 if (is_array($media)) {
307 if (is_array($media['tmp_name'])) {
308 $src = $media['tmp_name'][0];
310 $src = $media['tmp_name'];
312 if (is_array($media['name'])) {
313 $filename = basename($media['name'][0]);
315 $filename = basename($media['name']);
317 if (is_array($media['size'])) {
318 $filesize = intval($media['size'][0]);
320 $filesize = intval($media['size']);
322 if (is_array($media['type'])) {
323 $filetype = $media['type'][0];
325 $filetype = $media['type'];
329 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
332 "File upload src: " . $src . " - filename: " . $filename .
333 " - size: " . $filesize . " - type: " . $filetype);
335 // check if there was a php upload error
336 if ($filesize == 0 && $media['error'] == 1) {
337 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
339 // check against max upload size within Friendica instance
340 $maximagesize = DI::config()->get('system', 'maximagesize');
341 if ($maximagesize && ($filesize > $maximagesize)) {
342 $formattedBytes = Strings::formatBytes($maximagesize);
343 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
346 // create Photo instance with the data of the image
347 $imagedata = @file_get_contents($src);
348 $Image = new Image($imagedata, $filetype);
349 if (!$Image->isValid()) {
350 throw new InternalServerErrorException("unable to process image data");
353 // check orientation of image
354 $Image->orient($src);
357 // check max length of images on server
358 $max_length = DI::config()->get('system', 'max_image_length');
359 if ($max_length > 0) {
360 $Image->scaleDown($max_length);
361 logger::info("File upload: Scaling picture to new size " . $max_length);
363 $width = $Image->getWidth();
364 $height = $Image->getHeight();
366 // create a new resource-id if not already provided
367 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
369 if ($mediatype == "photo") {
370 // upload normal image (scales 0, 1, 2)
371 logger::info("photo upload: starting new photo upload");
373 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
375 logger::notice("photo upload: image upload with scale 0 (original size) failed");
377 if ($width > 640 || $height > 640) {
378 $Image->scaleDown(640);
379 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
381 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
385 if ($width > 320 || $height > 320) {
386 $Image->scaleDown(320);
387 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
389 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
392 logger::info("photo upload: new photo upload ended");
393 } elseif ($mediatype == "profileimage") {
394 // upload profile image (scales 4, 5, 6)
395 logger::info("photo upload: starting new profile image upload");
397 if ($width > 300 || $height > 300) {
398 $Image->scaleDown(300);
399 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
401 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
405 if ($width > 80 || $height > 80) {
406 $Image->scaleDown(80);
407 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
409 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
413 if ($width > 48 || $height > 48) {
414 $Image->scaleDown(48);
415 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
417 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
420 $Image->__destruct();
421 logger::info("photo upload: new profile image upload ended");
425 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
426 if ($photo_id == null && $mediatype == "photo") {
427 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid);
429 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
430 return prepare_photo_data($type, false, $resource_id, $uid);
432 throw new InternalServerErrorException("image upload failed");
438 * @param string $hash
439 * @param string $allow_cid
440 * @param string $deny_cid
441 * @param string $allow_gid
442 * @param string $deny_gid
443 * @param string $filetype
444 * @param boolean $visibility
446 * @throws InternalServerErrorException
448 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid)
450 // get data about the api authenticated user
451 $uri = Item::newURI(intval($uid));
452 $owner_record = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
455 $arr['guid'] = System::createUUID();
456 $arr['uid'] = intval($uid);
458 $arr['type'] = 'photo';
460 $arr['resource-id'] = $hash;
461 $arr['contact-id'] = $owner_record['id'];
462 $arr['owner-name'] = $owner_record['name'];
463 $arr['owner-link'] = $owner_record['url'];
464 $arr['owner-avatar'] = $owner_record['thumb'];
465 $arr['author-name'] = $owner_record['name'];
466 $arr['author-link'] = $owner_record['url'];
467 $arr['author-avatar'] = $owner_record['thumb'];
469 $arr['allow_cid'] = $allow_cid;
470 $arr['allow_gid'] = $allow_gid;
471 $arr['deny_cid'] = $deny_cid;
472 $arr['deny_gid'] = $deny_gid;
473 $arr['visible'] = $visibility;
477 'image/jpeg' => 'jpg',
478 'image/png' => 'png',
482 // adds link to the thumbnail scale photo
483 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
484 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
487 // do the magic for storing the item in the database and trigger the federation to other contacts
493 * @param string $type
495 * @param string $photo_id
498 * @throws BadRequestException
499 * @throws ForbiddenException
500 * @throws ImagickException
501 * @throws InternalServerErrorException
502 * @throws NotFoundException
503 * @throws UnauthorizedException
505 function prepare_photo_data($type, $scale, $photo_id, $uid)
507 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
508 $data_sql = ($scale === false ? "" : "data, ");
510 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
511 // clients needs to convert this in their way for further processing
512 $r = DBA::toArray(DBA::p(
513 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
514 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
515 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
516 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
517 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
518 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
524 'image/jpeg' => 'jpg',
525 'image/png' => 'png',
529 // prepare output data for photo
530 if (DBA::isResult($r)) {
531 $data = ['photo' => $r[0]];
532 $data['photo']['id'] = $data['photo']['resource-id'];
533 if ($scale !== false) {
534 $data['photo']['data'] = base64_encode($data['photo']['data']);
536 unset($data['photo']['datasize']); //needed only with scale param
538 if ($type == "xml") {
539 $data['photo']['links'] = [];
540 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
541 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
543 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
546 $data['photo']['link'] = [];
547 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
549 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
550 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
554 unset($data['photo']['resource-id']);
555 unset($data['photo']['minscale']);
556 unset($data['photo']['maxscale']);
558 throw new NotFoundException();
561 // retrieve item element for getting activities (like, dislike etc.) related to photo
562 $condition = ['uid' => $uid, 'resource-id' => $photo_id];
563 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
564 if (!DBA::isResult($item)) {
565 throw new NotFoundException('Photo-related item not found.');
568 $data['photo']['friendica_activities'] = DI::friendicaActivities()->createFromUriId($item['uri-id'], $item['uid'], $type);
570 // retrieve comments on photo
571 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
572 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
574 $statuses = Post::selectForUser($uid, [], $condition);
576 // prepare output of comments
578 while ($status = DBA::fetch($statuses)) {
579 $commentData[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'])->toArray();
581 DBA::close($statuses);
584 if ($type == "xml") {
586 foreach ($commentData as $comment) {
587 $comments[$k++ . ":comment"] = $comment;
590 foreach ($commentData as $comment) {
591 $comments[] = $comment;
594 $data['photo']['friendica_comments'] = $comments;
596 // include info if rights on photo and rights on item are mismatching
597 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
598 $data['photo']['deny_cid'] != $item['deny_cid'] ||
599 $data['photo']['allow_gid'] != $item['allow_gid'] ||
600 $data['photo']['deny_gid'] != $item['deny_gid'];
601 $data['photo']['rights_mismatch'] = $rights_mismatch;
608 * @param string $text
611 * @throws InternalServerErrorException
613 function api_clean_plain_items($text)
615 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
617 $text = BBCode::cleanPictureLinks($text);
618 $URLSearchString = "^\[\]";
620 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
622 if ($include_entities == "true") {
623 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
626 // Simplify "attachment" element
627 $text = BBCode::removeAttachment($text);
633 * Add a new group to the database.
635 * @param string $name Group name
636 * @param int $uid User ID
637 * @param array $users List of users to add to the group
640 * @throws BadRequestException
642 function group_create($name, $uid, $users = [])
644 // error if no name specified
646 throw new BadRequestException('group name not specified');
649 // error message if specified group name already exists
650 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
651 throw new BadRequestException('group name already exists');
654 // Check if the group needs to be reactivated
655 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
656 $reactivate_group = true;
660 $ret = Group::create($uid, $name);
662 $gid = Group::getIdByName($uid, $name);
664 throw new BadRequestException('other API error');
668 $erroraddinguser = false;
670 foreach ($users as $user) {
672 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
673 Group::addMember($gid, $cid);
675 $erroraddinguser = true;
676 $errorusers[] = $cid;
680 // return success message incl. missing users in array
681 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
683 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
691 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
692 * returns a 401 status code and an error message if not.
694 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
696 * @param string $type Return type (atom, rss, xml, json)
697 * @return array|string
698 * @throws BadRequestException
699 * @throws ForbiddenException
700 * @throws ImagickException
701 * @throws InternalServerErrorException
702 * @throws UnauthorizedException
704 function api_account_verify_credentials($type)
706 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
707 $uid = BaseApi::getCurrentUserID();
709 $skip_status = $_REQUEST['skip_status'] ?? false;
711 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
713 // "verified" isn't used here in the standard
714 unset($user_info["verified"]);
716 // "uid" is only needed for some internal stuff, so remove it from here
717 unset($user_info['uid']);
719 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
722 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
725 * Deprecated function to upload media.
727 * @param string $type Return type (atom, rss, xml, json)
729 * @return array|string
730 * @throws BadRequestException
731 * @throws ForbiddenException
732 * @throws ImagickException
733 * @throws InternalServerErrorException
734 * @throws UnauthorizedException
736 function api_statuses_mediap($type)
738 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
739 $uid = BaseApi::getCurrentUserID();
743 $_REQUEST['profile_uid'] = $uid;
744 $_REQUEST['api_source'] = true;
745 $txt = $_REQUEST['status'] ?? '';
747 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
748 $txt = HTML::toBBCodeVideo($txt);
749 $config = HTMLPurifier_Config::createDefault();
750 $config->set('Cache.DefinitionImpl', null);
751 $purifier = new HTMLPurifier($config);
752 $txt = $purifier->purify($txt);
754 $txt = HTML::toBBCode($txt);
756 $picture = wall_upload_post($a, false);
758 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
759 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
760 $item_id = item_post($a);
762 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
764 // output the post that we just posted.
765 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
766 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
769 /// @TODO move this to top of file or somewhere better!
770 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
773 * Updates the user’s current status.
775 * @param string $type Return type (atom, rss, xml, json)
777 * @return array|string
778 * @throws BadRequestException
779 * @throws ForbiddenException
780 * @throws ImagickException
781 * @throws InternalServerErrorException
782 * @throws TooManyRequestsException
783 * @throws UnauthorizedException
784 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
786 function api_statuses_update($type)
788 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
789 $uid = BaseApi::getCurrentUserID();
793 // convert $_POST array items to the form we use for web posts.
794 if (!empty($_REQUEST['htmlstatus'])) {
795 $txt = $_REQUEST['htmlstatus'];
796 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
797 $txt = HTML::toBBCodeVideo($txt);
799 $config = HTMLPurifier_Config::createDefault();
800 $config->set('Cache.DefinitionImpl', null);
802 $purifier = new HTMLPurifier($config);
803 $txt = $purifier->purify($txt);
805 $_REQUEST['body'] = HTML::toBBCode($txt);
808 $_REQUEST['body'] = $_REQUEST['status'] ?? null;
811 $_REQUEST['title'] = $_REQUEST['title'] ?? null;
813 $parent = $_REQUEST['in_reply_to_status_id'] ?? null;
815 // Twidere sends "-1" if it is no reply ...
820 if (ctype_digit($parent)) {
821 $_REQUEST['parent'] = $parent;
823 $_REQUEST['parent_uri'] = $parent;
826 if (!empty($_REQUEST['lat']) && !empty($_REQUEST['long'])) {
827 $_REQUEST['coord'] = sprintf("%s %s", $_REQUEST['lat'], $_REQUEST['long']);
829 $_REQUEST['profile_uid'] = $uid;
832 // Check for throttling (maximum posts per day, week and month)
833 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
834 if ($throttle_day > 0) {
835 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
837 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
838 $posts_day = Post::count($condition);
840 if ($posts_day > $throttle_day) {
841 logger::info('Daily posting limit reached for user ' . $uid);
842 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
843 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));
847 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
848 if ($throttle_week > 0) {
849 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
851 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
852 $posts_week = Post::count($condition);
854 if ($posts_week > $throttle_week) {
855 logger::info('Weekly posting limit reached for user ' . $uid);
856 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
857 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));
861 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
862 if ($throttle_month > 0) {
863 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
865 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
866 $posts_month = Post::count($condition);
868 if ($posts_month > $throttle_month) {
869 logger::info('Monthly posting limit reached for user ' . $uid);
870 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
871 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));
876 if (!empty($_REQUEST['media_ids'])) {
877 $ids = explode(',', $_REQUEST['media_ids']);
878 } elseif (!empty($_FILES['media'])) {
879 // upload the image if we have one
880 $picture = wall_upload_post($a, false);
881 if (is_array($picture)) {
882 $ids[] = $picture['id'];
890 foreach ($ids as $id) {
891 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
892 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
893 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
894 ORDER BY `photo`.`width` DESC LIMIT 2", $id, $uid));
896 if (!empty($media)) {
897 $ressources[] = $media[0]['resource-id'];
898 $phototypes = Images::supportedTypes();
899 $ext = $phototypes[$media[0]['type']];
901 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
902 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
903 'size' => $media[0]['datasize'],
904 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
905 'description' => $media[0]['desc'] ?? '',
906 'width' => $media[0]['width'],
907 'height' => $media[0]['height']];
909 if (count($media) > 1) {
910 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
911 $attachment['preview-width'] = $media[1]['width'];
912 $attachment['preview-height'] = $media[1]['height'];
914 $attachments[] = $attachment;
918 // We have to avoid that the post is rejected because of an empty body
919 if (empty($_REQUEST['body'])) {
920 $_REQUEST['body'] = '[hr]';
924 if (!empty($attachments)) {
925 $_REQUEST['attachments'] = $attachments;
928 // set this so that the item_post() function is quiet and doesn't redirect or emit json
930 $_REQUEST['api_source'] = true;
932 if (empty($_REQUEST['source'])) {
933 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
936 // call out normal post function
937 $item_id = item_post($a);
939 if (!empty($ressources) && !empty($item_id)) {
940 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
941 foreach ($ressources as $ressource) {
942 Photo::setPermissionForRessource($ressource, $uid, $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
946 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
948 // output the post that we just posted.
949 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
950 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
953 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
954 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
957 * Uploads an image to Friendica.
960 * @throws BadRequestException
961 * @throws ForbiddenException
962 * @throws ImagickException
963 * @throws InternalServerErrorException
964 * @throws UnauthorizedException
965 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
967 function api_media_upload()
969 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
971 if (empty($_FILES['media'])) {
973 throw new BadRequestException("No media.");
976 $media = wall_upload_post(DI::app(), false);
979 throw new InternalServerErrorException();
983 $returndata["media_id"] = $media["id"];
984 $returndata["media_id_string"] = (string)$media["id"];
985 $returndata["size"] = $media["size"];
986 $returndata["image"] = ["w" => $media["width"],
987 "h" => $media["height"],
988 "image_type" => $media["type"],
989 "friendica_preview_url" => $media["preview"]];
991 Logger::info('Media uploaded', ['return' => $returndata]);
993 return ["media" => $returndata];
996 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
999 * Updates media meta data (picture descriptions)
1001 * @param string $type Return type (atom, rss, xml, json)
1003 * @return array|string
1004 * @throws BadRequestException
1005 * @throws ForbiddenException
1006 * @throws ImagickException
1007 * @throws InternalServerErrorException
1008 * @throws TooManyRequestsException
1009 * @throws UnauthorizedException
1010 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1012 * @todo Compare the corresponding Twitter function for correct return values
1014 function api_media_metadata_create($type)
1016 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1017 $uid = BaseApi::getCurrentUserID();
1019 $postdata = Network::postdata();
1021 if (empty($postdata)) {
1022 throw new BadRequestException("No post data");
1025 $data = json_decode($postdata, true);
1027 throw new BadRequestException("Invalid post data");
1030 if (empty($data['media_id']) || empty($data['alt_text'])) {
1031 throw new BadRequestException("Missing post data values");
1034 if (empty($data['alt_text']['text'])) {
1035 throw new BadRequestException("No alt text.");
1038 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1040 $condition = ['id' => $data['media_id'], 'uid' => $uid];
1041 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1042 if (!DBA::isResult($photo)) {
1043 throw new BadRequestException("Metadata not found.");
1046 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1049 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1052 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1053 * The author's most recent status will be returned inline.
1055 * @param string $type Return type (atom, rss, xml, json)
1056 * @return array|string
1057 * @throws BadRequestException
1058 * @throws ImagickException
1059 * @throws InternalServerErrorException
1060 * @throws UnauthorizedException
1061 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1063 function api_users_show($type)
1065 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1066 $uid = BaseApi::getCurrentUserID();
1068 $user_info = DI::twitterUser()->createFromUserId($uid, false)->toArray();
1070 // "uid" is only needed for some internal stuff, so remove it from here
1071 unset($user_info['uid']);
1073 return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
1076 api_register_func('api/users/show', 'api_users_show');
1077 api_register_func('api/externalprofile/show', 'api_users_show');
1080 * Search a public user account.
1082 * @param string $type Return type (atom, rss, xml, json)
1084 * @return array|string
1085 * @throws BadRequestException
1086 * @throws ImagickException
1087 * @throws InternalServerErrorException
1088 * @throws UnauthorizedException
1089 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1091 function api_users_search($type)
1093 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1094 $uid = BaseApi::getCurrentUserID();
1098 if (!empty($_GET['q'])) {
1099 $contacts = Contact::selectToArray(
1102 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1110 if (DBA::isResult($contacts)) {
1112 foreach ($contacts as $contact) {
1113 $user_info = DI::twitterUser()->createFromContactId($contact['id'], $uid, false)->toArray();
1115 if ($type == 'xml') {
1116 $userlist[$k++ . ':user'] = $user_info;
1118 $userlist[] = $user_info;
1121 $userlist = ['users' => $userlist];
1123 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1126 throw new BadRequestException('No search term specified.');
1129 return DI::apiResponse()->formatData('users', $type, $userlist);
1132 api_register_func('api/users/search', 'api_users_search');
1135 * Return user objects
1137 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1139 * @param string $type Return format: json or xml
1141 * @return array|string
1142 * @throws BadRequestException
1143 * @throws ImagickException
1144 * @throws InternalServerErrorException
1145 * @throws NotFoundException if the results are empty.
1146 * @throws UnauthorizedException
1148 function api_users_lookup($type)
1150 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1151 $uid = BaseApi::getCurrentUserID();
1155 if (!empty($_REQUEST['user_id'])) {
1156 foreach (explode(',', $_REQUEST['user_id']) as $cid) {
1157 if (!empty($cid) && is_numeric($cid)) {
1158 $users[] = DI::twitterUser()->createFromContactId((int)$cid, $uid, false)->toArray();
1163 if (empty($users)) {
1164 throw new NotFoundException;
1167 return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
1170 api_register_func('api/users/lookup', 'api_users_lookup', true);
1173 * Returns statuses that match a specified query.
1175 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1177 * @param string $type Return format: json, xml, atom, rss
1179 * @return array|string
1180 * @throws BadRequestException if the "q" parameter is missing.
1181 * @throws ForbiddenException
1182 * @throws ImagickException
1183 * @throws InternalServerErrorException
1184 * @throws UnauthorizedException
1186 function api_search($type)
1188 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1189 $uid = BaseApi::getCurrentUserID();
1191 if (empty($_REQUEST['q'])) {
1192 throw new BadRequestException('q parameter is required.');
1195 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1198 $data['status'] = [];
1200 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1201 if (!empty($_REQUEST['rpp'])) {
1202 $count = $_REQUEST['rpp'];
1203 } elseif (!empty($_REQUEST['count'])) {
1204 $count = $_REQUEST['count'];
1207 $since_id = $_REQUEST['since_id'] ?? 0;
1208 $max_id = $_REQUEST['max_id'] ?? 0;
1209 $page = $_REQUEST['page'] ?? 1;
1211 $start = max(0, ($page - 1) * $count);
1213 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1214 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1215 $searchTerm = $matches[1];
1216 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, $uid];
1217 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1219 while ($tag = DBA::fetch($tags)) {
1220 $uriids[] = $tag['uri-id'];
1224 if (empty($uriids)) {
1225 return DI::apiResponse()->formatData('statuses', $type, $data);
1228 $condition = ['uri-id' => $uriids];
1229 if ($exclude_replies) {
1230 $condition['gravity'] = GRAVITY_PARENT;
1233 $params['group_by'] = ['uri-id'];
1235 $condition = ["`id` > ?
1236 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1237 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1238 AND `body` LIKE CONCAT('%',?,'%')",
1239 $since_id, $uid, $_REQUEST['q']];
1241 $condition[0] .= ' AND `id` <= ?';
1242 $condition[] = $max_id;
1248 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1249 $id = Item::fetchByLink($searchTerm, $uid);
1252 $id = Item::fetchByLink($searchTerm);
1256 $statuses = Post::select([], ['id' => $id]);
1260 $statuses = $statuses ?: Post::selectForUser($uid, [], $condition, $params);
1262 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1265 while ($status = DBA::fetch($statuses)) {
1266 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1268 DBA::close($statuses);
1270 $data['status'] = $ret;
1272 return DI::apiResponse()->formatData('statuses', $type, $data);
1275 api_register_func('api/search/tweets', 'api_search', true);
1276 api_register_func('api/search', 'api_search', true);
1279 * Returns the most recent statuses posted by the user and the users they follow.
1281 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1283 * @param string $type Return type (atom, rss, xml, json)
1285 * @return array|string
1286 * @throws BadRequestException
1287 * @throws ForbiddenException
1288 * @throws ImagickException
1289 * @throws InternalServerErrorException
1290 * @throws UnauthorizedException
1291 * @todo Optional parameters
1292 * @todo Add reply info
1294 function api_statuses_home_timeline($type)
1296 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1297 $uid = BaseApi::getCurrentUserID();
1299 // get last network messages
1302 $count = $_REQUEST['count'] ?? 20;
1303 $page = $_REQUEST['page']?? 0;
1304 $since_id = $_REQUEST['since_id'] ?? 0;
1305 $max_id = $_REQUEST['max_id'] ?? 0;
1306 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1307 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1309 $start = max(0, ($page - 1) * $count);
1311 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1312 $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1315 $condition[0] .= " AND `id` <= ?";
1316 $condition[] = $max_id;
1318 if ($exclude_replies) {
1319 $condition[0] .= ' AND `gravity` = ?';
1320 $condition[] = GRAVITY_PARENT;
1322 if ($conversation_id > 0) {
1323 $condition[0] .= " AND `parent` = ?";
1324 $condition[] = $conversation_id;
1327 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1328 $statuses = Post::selectForUser($uid, [], $condition, $params);
1330 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1334 while ($status = DBA::fetch($statuses)) {
1335 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1336 $idarray[] = intval($status['id']);
1338 DBA::close($statuses);
1340 if (!empty($idarray)) {
1341 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1343 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1347 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1351 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1352 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1355 * Returns the most recent statuses from public users.
1357 * @param string $type Return type (atom, rss, xml, json)
1359 * @return array|string
1360 * @throws BadRequestException
1361 * @throws ForbiddenException
1362 * @throws ImagickException
1363 * @throws InternalServerErrorException
1364 * @throws UnauthorizedException
1366 function api_statuses_public_timeline($type)
1368 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1369 $uid = BaseApi::getCurrentUserID();
1371 // get last network messages
1374 $count = $_REQUEST['count'] ?? 20;
1375 $page = $_REQUEST['page'] ?? 1;
1376 $since_id = $_REQUEST['since_id'] ?? 0;
1377 $max_id = $_REQUEST['max_id'] ?? 0;
1378 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1379 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1381 $start = max(0, ($page - 1) * $count);
1383 if ($exclude_replies && !$conversation_id) {
1384 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1385 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1388 $condition[0] .= " AND `id` <= ?";
1389 $condition[] = $max_id;
1392 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1393 $statuses = Post::selectForUser($uid, [], $condition, $params);
1395 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1396 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1399 $condition[0] .= " AND `id` <= ?";
1400 $condition[] = $max_id;
1402 if ($conversation_id > 0) {
1403 $condition[0] .= " AND `parent` = ?";
1404 $condition[] = $conversation_id;
1407 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1408 $statuses = Post::selectForUser($uid, [], $condition, $params);
1411 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1414 while ($status = DBA::fetch($statuses)) {
1415 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1417 DBA::close($statuses);
1419 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1422 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1425 * Returns the most recent statuses posted by users this node knows about.
1427 * @param string $type Return format: json, xml, atom, rss
1428 * @return array|string
1429 * @throws BadRequestException
1430 * @throws ForbiddenException
1431 * @throws ImagickException
1432 * @throws InternalServerErrorException
1433 * @throws UnauthorizedException
1435 function api_statuses_networkpublic_timeline($type)
1437 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1438 $uid = BaseApi::getCurrentUserID();
1440 $since_id = $_REQUEST['since_id'] ?? 0;
1441 $max_id = $_REQUEST['max_id'] ?? 0;
1444 $count = $_REQUEST['count'] ?? 20;
1445 $page = $_REQUEST['page'] ?? 1;
1447 $start = max(0, ($page - 1) * $count);
1449 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1450 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1453 $condition[0] .= " AND `id` <= ?";
1454 $condition[] = $max_id;
1457 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1458 $statuses = Post::selectForUser($uid, Item::DISPLAY_FIELDLIST, $condition, $params);
1460 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1463 while ($status = DBA::fetch($statuses)) {
1464 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1466 DBA::close($statuses);
1468 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1471 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1474 * Returns a single status.
1476 * @param string $type Return type (atom, rss, xml, json)
1478 * @return array|string
1479 * @throws BadRequestException
1480 * @throws ForbiddenException
1481 * @throws ImagickException
1482 * @throws InternalServerErrorException
1483 * @throws UnauthorizedException
1484 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1486 function api_statuses_show($type)
1488 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1489 $uid = BaseApi::getCurrentUserID();
1492 $id = intval(DI::args()->getArgv()[3] ?? 0);
1495 $id = intval($_REQUEST['id'] ?? 0);
1500 $id = intval(DI::args()->getArgv()[4] ?? 0);
1503 logger::notice('API: api_statuses_show: ' . $id);
1505 $conversation = !empty($_REQUEST['conversation']);
1507 // try to fetch the item for the local user - or the public item, if there is no local one
1508 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1509 if (!DBA::isResult($uri_item)) {
1510 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1513 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1514 if (!DBA::isResult($item)) {
1515 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1520 if ($conversation) {
1521 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1522 $params = ['order' => ['id' => true]];
1524 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1528 $statuses = Post::selectForUser($uid, [], $condition, $params);
1530 /// @TODO How about copying this to above methods which don't check $r ?
1531 if (!DBA::isResult($statuses)) {
1532 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1535 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1538 while ($status = DBA::fetch($statuses)) {
1539 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1541 DBA::close($statuses);
1543 if ($conversation) {
1544 $data = ['status' => $ret];
1545 return DI::apiResponse()->formatData("statuses", $type, $data);
1547 $data = ['status' => $ret[0]];
1548 return DI::apiResponse()->formatData("status", $type, $data);
1552 api_register_func('api/statuses/show', 'api_statuses_show', true);
1556 * @param string $type Return type (atom, rss, xml, json)
1558 * @return array|string
1559 * @throws BadRequestException
1560 * @throws ForbiddenException
1561 * @throws ImagickException
1562 * @throws InternalServerErrorException
1563 * @throws UnauthorizedException
1564 * @todo nothing to say?
1566 function api_conversation_show($type)
1568 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1569 $uid = BaseApi::getCurrentUserID();
1572 $id = intval(DI::args()->getArgv()[3] ?? 0);
1573 $since_id = intval($_REQUEST['since_id'] ?? 0);
1574 $max_id = intval($_REQUEST['max_id'] ?? 0);
1575 $count = intval($_REQUEST['count'] ?? 20);
1576 $page = intval($_REQUEST['page'] ?? 1);
1578 $start = max(0, ($page - 1) * $count);
1581 $id = intval($_REQUEST['id'] ?? 0);
1586 $id = intval(DI::args()->getArgv()[4] ?? 0);
1589 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1591 // try to fetch the item for the local user - or the public item, if there is no local one
1592 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1593 if (!DBA::isResult($item)) {
1594 throw new BadRequestException("There is no status with the id $id.");
1597 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1598 if (!DBA::isResult($parent)) {
1599 throw new BadRequestException("There is no status with this id.");
1602 $id = $parent['id'];
1604 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1605 $id, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1608 $condition[0] .= " AND `id` <= ?";
1609 $condition[] = $max_id;
1612 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1613 $statuses = Post::selectForUser($uid, [], $condition, $params);
1615 if (!DBA::isResult($statuses)) {
1616 throw new BadRequestException("There is no status with id $id.");
1619 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1622 while ($status = DBA::fetch($statuses)) {
1623 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1625 DBA::close($statuses);
1627 $data = ['status' => $ret];
1628 return DI::apiResponse()->formatData("statuses", $type, $data);
1631 api_register_func('api/conversation/show', 'api_conversation_show', true);
1632 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1637 * @param string $type Return type (atom, rss, xml, json)
1639 * @return array|string
1640 * @throws BadRequestException
1641 * @throws ForbiddenException
1642 * @throws ImagickException
1643 * @throws InternalServerErrorException
1644 * @throws UnauthorizedException
1645 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1647 function api_statuses_repeat($type)
1649 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1650 $uid = BaseApi::getCurrentUserID();
1653 $id = intval(DI::args()->getArgv()[3] ?? 0);
1656 $id = intval($_REQUEST['id'] ?? 0);
1661 $id = intval(DI::args()->getArgv()[4] ?? 0);
1664 logger::notice('API: api_statuses_repeat: ' . $id);
1666 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1667 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1669 if (DBA::isResult($item) && !empty($item['body'])) {
1670 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1671 if (!Item::performActivity($id, 'announce', $uid)) {
1672 throw new InternalServerErrorException();
1677 if (strpos($item['body'], "[/share]") !== false) {
1678 $pos = strpos($item['body'], "[share");
1679 $post = substr($item['body'], $pos);
1681 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1683 if (!empty($item['title'])) {
1684 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1687 $post .= $item['body'];
1688 $post .= "[/share]";
1690 $_REQUEST['body'] = $post;
1691 $_REQUEST['profile_uid'] = $uid;
1692 $_REQUEST['api_source'] = true;
1694 if (empty($_REQUEST['source'])) {
1695 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
1698 $item_id = item_post(DI::app());
1701 throw new ForbiddenException();
1704 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1706 // output the post that we just posted.
1707 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
1708 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
1711 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1714 * Destroys a specific status.
1716 * @param string $type Return type (atom, rss, xml, json)
1718 * @return array|string
1719 * @throws BadRequestException
1720 * @throws ForbiddenException
1721 * @throws ImagickException
1722 * @throws InternalServerErrorException
1723 * @throws UnauthorizedException
1724 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1726 function api_statuses_destroy($type)
1728 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1729 $uid = BaseApi::getCurrentUserID();
1732 $id = intval(DI::args()->getArgv()[3] ?? 0);
1735 $id = intval($_REQUEST['id'] ?? 0);
1740 $id = intval(DI::args()->getArgv()[4] ?? 0);
1743 logger::notice('API: api_statuses_destroy: ' . $id);
1745 $ret = api_statuses_show($type);
1747 Item::deleteForUser(['id' => $id], $uid);
1752 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1755 * Returns the most recent mentions.
1757 * @param string $type Return type (atom, rss, xml, json)
1759 * @return array|string
1760 * @throws BadRequestException
1761 * @throws ForbiddenException
1762 * @throws ImagickException
1763 * @throws InternalServerErrorException
1764 * @throws UnauthorizedException
1765 * @see http://developer.twitter.com/doc/get/statuses/mentions
1767 function api_statuses_mentions($type)
1769 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1770 $uid = BaseApi::getCurrentUserID();
1772 // get last network messages
1775 $since_id = intval($_REQUEST['since_id'] ?? 0);
1776 $max_id = intval($_REQUEST['max_id'] ?? 0);
1777 $count = intval($_REQUEST['count'] ?? 20);
1778 $page = intval($_REQUEST['page'] ?? 1);
1780 $start = max(0, ($page - 1) * $count);
1782 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1783 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1784 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1787 GRAVITY_PARENT, GRAVITY_COMMENT,
1789 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1790 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1791 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1796 $query .= " AND `id` <= ?";
1797 $condition[] = $max_id;
1800 array_unshift($condition, $query);
1802 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1803 $statuses = Post::selectForUser($uid, [], $condition, $params);
1805 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1808 while ($status = DBA::fetch($statuses)) {
1809 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1811 DBA::close($statuses);
1813 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1816 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1817 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1820 * Returns the most recent statuses posted by the user.
1822 * @param string $type Either "json" or "xml"
1823 * @return string|array
1824 * @throws BadRequestException
1825 * @throws ForbiddenException
1826 * @throws ImagickException
1827 * @throws InternalServerErrorException
1828 * @throws UnauthorizedException
1829 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1831 function api_statuses_user_timeline($type)
1833 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1834 $uid = BaseApi::getCurrentUserID();
1836 Logger::info('api_statuses_user_timeline', ['api_user' => $uid, '_REQUEST' => $_REQUEST]);
1838 $cid = BaseApi::getContactIDForSearchterm($_REQUEST['screen_name'] ?? '', $_REQUEST['user_id'] ?? 0, $uid);
1839 $since_id = $_REQUEST['since_id'] ?? 0;
1840 $max_id = $_REQUEST['max_id'] ?? 0;
1841 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1842 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1845 $count = $_REQUEST['count'] ?? 20;
1846 $page = $_REQUEST['page'] ?? 1;
1848 $start = max(0, ($page - 1) * $count);
1850 $condition = ["(`uid` = ? OR (`uid` = ? AND NOT `global`)) AND `gravity` IN (?, ?) AND `id` > ? AND `author-id` = ?",
1851 0, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $cid];
1853 if ($exclude_replies) {
1854 $condition[0] .= ' AND `gravity` = ?';
1855 $condition[] = GRAVITY_PARENT;
1858 if ($conversation_id > 0) {
1859 $condition[0] .= " AND `parent` = ?";
1860 $condition[] = $conversation_id;
1864 $condition[0] .= " AND `id` <= ?";
1865 $condition[] = $max_id;
1867 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1868 $statuses = Post::selectForUser($uid, [], $condition, $params);
1870 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1873 while ($status = DBA::fetch($statuses)) {
1874 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1876 DBA::close($statuses);
1878 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1881 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1884 * Star/unstar an item.
1885 * param: id : id of the item
1887 * @param string $type Return type (atom, rss, xml, json)
1889 * @return array|string
1890 * @throws BadRequestException
1891 * @throws ForbiddenException
1892 * @throws ImagickException
1893 * @throws InternalServerErrorException
1894 * @throws UnauthorizedException
1895 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1897 function api_favorites_create_destroy($type)
1899 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1900 $uid = BaseApi::getCurrentUserID();
1902 // for versioned api.
1903 /// @TODO We need a better global soluton
1904 $action_argv_id = 2;
1905 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1906 $action_argv_id = 3;
1909 if (DI::args()->getArgc() <= $action_argv_id) {
1910 throw new BadRequestException("Invalid request.");
1912 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1913 if (DI::args()->getArgc() == $action_argv_id + 2) {
1914 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1916 $itemid = intval($_REQUEST['id'] ?? 0);
1919 $item = Post::selectFirstForUser($uid, [], ['id' => $itemid, 'uid' => $uid]);
1921 if (!DBA::isResult($item)) {
1922 throw new BadRequestException("Invalid item.");
1927 $item['starred'] = 1;
1930 $item['starred'] = 0;
1933 throw new BadRequestException("Invalid action ".$action);
1936 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1939 throw new InternalServerErrorException("DB error");
1942 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1944 $ret = DI::twitterStatus()->createFromUriId($item['uri-id'], $item['uid'], $include_entities)->toArray();
1946 return DI::apiResponse()->formatData("status", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1949 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1950 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1953 * Returns the most recent favorite statuses.
1955 * @param string $type Return type (atom, rss, xml, json)
1957 * @return string|array
1958 * @throws BadRequestException
1959 * @throws ForbiddenException
1960 * @throws ImagickException
1961 * @throws InternalServerErrorException
1962 * @throws UnauthorizedException
1964 function api_favorites($type)
1966 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1967 $uid = BaseApi::getCurrentUserID();
1969 // in friendica starred item are private
1970 // return favorites only for self
1971 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites']);
1974 $since_id = $_REQUEST['since_id'] ?? 0;
1975 $max_id = $_REQUEST['max_id'] ?? 0;
1976 $count = $_GET['count'] ?? 20;
1977 $page = $_REQUEST['page'] ?? 1;
1979 $start = max(0, ($page - 1) * $count);
1981 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
1982 $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1984 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1987 $condition[0] .= " AND `id` <= ?";
1988 $condition[] = $max_id;
1991 $statuses = Post::selectForUser($uid, [], $condition, $params);
1993 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1996 while ($status = DBA::fetch($statuses)) {
1997 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1999 DBA::close($statuses);
2001 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
2004 api_register_func('api/favorites', 'api_favorites', true);
2007 * Returns all lists the user subscribes to.
2009 * @param string $type Return type (atom, rss, xml, json)
2011 * @return array|string
2012 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2014 function api_lists_list($type)
2017 /// @TODO $ret is not filled here?
2018 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2021 api_register_func('api/lists/list', 'api_lists_list', true);
2022 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2025 * Returns all groups the user owns.
2027 * @param string $type Return type (atom, rss, xml, json)
2029 * @return array|string
2030 * @throws BadRequestException
2031 * @throws ForbiddenException
2032 * @throws ImagickException
2033 * @throws InternalServerErrorException
2034 * @throws UnauthorizedException
2035 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2037 function api_lists_ownerships($type)
2039 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2040 $uid = BaseApi::getCurrentUserID();
2043 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2045 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2047 // loop through all groups
2049 foreach ($groups as $group) {
2050 if ($group['visible']) {
2056 'name' => $group['name'],
2057 'id' => intval($group['id']),
2058 'id_str' => (string) $group['id'],
2059 'user' => $user_info,
2063 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2066 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2069 * Returns recent statuses from users in the specified group.
2071 * @param string $type Return type (atom, rss, xml, json)
2073 * @return array|string
2074 * @throws BadRequestException
2075 * @throws ForbiddenException
2076 * @throws ImagickException
2077 * @throws InternalServerErrorException
2078 * @throws UnauthorizedException
2079 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2081 function api_lists_statuses($type)
2083 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2084 $uid = BaseApi::getCurrentUserID();
2086 if (empty($_REQUEST['list_id'])) {
2087 throw new BadRequestException('list_id not specified');
2091 $count = $_REQUEST['count'] ?? 20;
2092 $page = $_REQUEST['page'] ?? 1;
2093 $since_id = $_REQUEST['since_id'] ?? 0;
2094 $max_id = $_REQUEST['max_id'] ?? 0;
2095 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2096 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2098 $start = max(0, ($page - 1) * $count);
2100 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2101 $gids = array_column($groups, 'contact-id');
2102 $condition = ['uid' => $uid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2103 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2106 $condition[0] .= " AND `id` <= ?";
2107 $condition[] = $max_id;
2109 if ($exclude_replies > 0) {
2110 $condition[0] .= ' AND `gravity` = ?';
2111 $condition[] = GRAVITY_PARENT;
2113 if ($conversation_id > 0) {
2114 $condition[0] .= " AND `parent` = ?";
2115 $condition[] = $conversation_id;
2118 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2119 $statuses = Post::selectForUser($uid, [], $condition, $params);
2121 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
2124 while ($status = DBA::fetch($statuses)) {
2125 $items[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
2127 DBA::close($statuses);
2129 return DI::apiResponse()->formatData("statuses", $type, ['status' => $items], Contact::getPublicIdByUserId($uid));
2132 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2135 * Returns either the friends of the follower list
2137 * Considers friends and followers lists to be private and won't return
2138 * anything if any user_id parameter is passed.
2140 * @param string $qtype Either "friends" or "followers"
2141 * @return boolean|array
2142 * @throws BadRequestException
2143 * @throws ForbiddenException
2144 * @throws ImagickException
2145 * @throws InternalServerErrorException
2146 * @throws UnauthorizedException
2148 function api_statuses_f($qtype)
2150 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2151 $uid = BaseApi::getCurrentUserID();
2154 $count = $_GET['count'] ?? 20;
2155 $page = $_GET['page'] ?? 1;
2157 $start = max(0, ($page - 1) * $count);
2159 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2160 /* this is to stop Hotot to load friends multiple times
2161 * I'm not sure if I'm missing return something or
2162 * is a bug in hotot. Workaround, meantime
2166 return array('$users' => $ret);*/
2171 if ($qtype == 'friends') {
2172 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2173 } elseif ($qtype == 'followers') {
2174 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2177 if ($qtype == 'blocks') {
2178 $sql_filter = 'AND `blocked` AND NOT `pending`';
2179 } elseif ($qtype == 'incoming') {
2180 $sql_filter = 'AND `pending`';
2182 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2185 // @todo This query most likely can be replaced with a Contact::select...
2186 $r = DBA::toArray(DBA::p(
2201 foreach ($r as $cid) {
2202 $user = DI::twitterUser()->createFromContactId($cid['id'], $uid, false)->toArray();
2203 // "uid" is only needed for some internal stuff, so remove it from here
2204 unset($user['uid']);
2211 return ['user' => $ret];
2215 * Returns the list of friends of the provided user
2217 * @deprecated By Twitter API in favor of friends/list
2219 * @param string $type Either "json" or "xml"
2220 * @return boolean|string|array
2221 * @throws BadRequestException
2222 * @throws ForbiddenException
2224 function api_statuses_friends($type)
2226 $data = api_statuses_f("friends");
2227 if ($data === false) {
2230 return DI::apiResponse()->formatData("users", $type, $data);
2233 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2236 * Returns the list of followers of the provided user
2238 * @deprecated By Twitter API in favor of friends/list
2240 * @param string $type Either "json" or "xml"
2241 * @return boolean|string|array
2242 * @throws BadRequestException
2243 * @throws ForbiddenException
2245 function api_statuses_followers($type)
2247 $data = api_statuses_f("followers");
2248 if ($data === false) {
2251 return DI::apiResponse()->formatData("users", $type, $data);
2254 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2257 * Returns the list of blocked users
2259 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
2261 * @param string $type Either "json" or "xml"
2263 * @return boolean|string|array
2264 * @throws BadRequestException
2265 * @throws ForbiddenException
2267 function api_blocks_list($type)
2269 $data = api_statuses_f('blocks');
2270 if ($data === false) {
2273 return DI::apiResponse()->formatData("users", $type, $data);
2276 api_register_func('api/blocks/list', 'api_blocks_list', true);
2279 * Returns the list of pending users IDs
2281 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
2283 * @param string $type Either "json" or "xml"
2285 * @return boolean|string|array
2286 * @throws BadRequestException
2287 * @throws ForbiddenException
2289 function api_friendships_incoming($type)
2291 $data = api_statuses_f('incoming');
2292 if ($data === false) {
2297 foreach ($data['user'] as $user) {
2298 $ids[] = $user['id'];
2301 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
2304 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
2307 * Sends a new direct message.
2309 * @param string $type Return type (atom, rss, xml, json)
2311 * @return array|string
2312 * @throws BadRequestException
2313 * @throws ForbiddenException
2314 * @throws ImagickException
2315 * @throws InternalServerErrorException
2316 * @throws NotFoundException
2317 * @throws UnauthorizedException
2318 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
2320 function api_direct_messages_new($type)
2322 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2323 $uid = BaseApi::getCurrentUserID();
2325 if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
2329 $sender = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2331 $cid = BaseApi::getContactIDForSearchterm($_POST['screen_name'] ?? '', $_POST['user_id'] ?? 0, $uid);
2333 throw new NotFoundException('Recipient not found');
2337 if (!empty($_REQUEST['replyto'])) {
2338 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
2339 $replyto = $mail['parent-uri'];
2340 $sub = $mail['title'];
2342 if (!empty($_REQUEST['title'])) {
2343 $sub = $_REQUEST['title'];
2345 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
2349 $cdata = Contact::getPublicAndUserContactID($cid, $uid);
2351 $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
2354 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
2355 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid, true)->toArray(), $sender);
2357 $ret = ["error" => $id];
2360 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2363 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
2366 * delete a direct_message from mail table through api
2368 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2369 * @return string|array
2370 * @throws BadRequestException
2371 * @throws ForbiddenException
2372 * @throws ImagickException
2373 * @throws InternalServerErrorException
2374 * @throws UnauthorizedException
2375 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
2377 function api_direct_messages_destroy($type)
2379 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2380 $uid = BaseApi::getCurrentUserID();
2383 $id = $_REQUEST['id'] ?? 0;
2385 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
2386 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
2387 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
2389 // error if no id or parenturi specified (for clients posting parent-uri as well)
2390 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
2391 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
2392 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2395 // BadRequestException if no id specified (for clients using Twitter API)
2397 throw new BadRequestException('Message id not specified');
2400 // add parent-uri to sql command if specified by calling app
2401 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
2403 // error message if specified id is not in database
2404 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
2405 if ($verbose == "true") {
2406 $answer = ['result' => 'error', 'message' => 'message id not in database'];
2407 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2409 /// @todo BadRequestException ok for Twitter API clients?
2410 throw new BadRequestException('message id not in database');
2414 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
2416 if ($verbose == "true") {
2419 $answer = ['result' => 'ok', 'message' => 'message deleted'];
2420 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
2422 $answer = ['result' => 'error', 'message' => 'unknown error'];
2423 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2426 /// @todo return JSON data like Twitter API not yet implemented
2429 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2434 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2435 * @return string|array
2436 * @throws HTTPException\BadRequestException
2437 * @throws HTTPException\ExpectationFailedException
2438 * @throws HTTPException\ForbiddenException
2439 * @throws HTTPException\InternalServerErrorException
2440 * @throws HTTPException\NotFoundException
2441 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
2443 function api_friendships_destroy($type)
2445 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2446 $uid = BaseApi::getCurrentUserID();
2448 $owner = User::getOwnerDataById($uid);
2450 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
2451 throw new HTTPException\NotFoundException('Error Processing Request');
2454 $contact_id = $_REQUEST['user_id'] ?? 0;
2456 if (empty($contact_id)) {
2457 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
2458 throw new HTTPException\BadRequestException('no user_id specified');
2461 // Get Contact by given id
2462 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
2464 if(!DBA::isResult($contact)) {
2465 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
2466 throw new HTTPException\NotFoundException('no contact found to given ID');
2469 $url = $contact['url'];
2471 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
2472 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
2473 Strings::normaliseLink($url), $url];
2474 $contact = DBA::selectFirst('contact', [], $condition);
2476 if (!DBA::isResult($contact)) {
2477 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
2478 throw new HTTPException\NotFoundException('Not following Contact');
2482 $result = Contact::terminateFriendship($owner, $contact);
2484 if ($result === null) {
2485 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
2486 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
2489 if ($result === false) {
2490 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
2492 } catch (Exception $e) {
2493 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
2494 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
2497 // "uid" is only needed for some internal stuff, so remove it from here
2498 unset($contact['uid']);
2500 // Set screen_name since Twidere requests it
2501 $contact['screen_name'] = $contact['nick'];
2503 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
2506 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
2510 * @param string $type Return type (atom, rss, xml, json)
2511 * @param string $box
2512 * @param string $verbose
2514 * @return array|string
2515 * @throws BadRequestException
2516 * @throws ForbiddenException
2517 * @throws ImagickException
2518 * @throws InternalServerErrorException
2519 * @throws UnauthorizedException
2521 function api_direct_messages_box($type, $box, $verbose)
2523 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2524 $uid = BaseApi::getCurrentUserID();
2527 $count = $_GET['count'] ?? 20;
2528 $page = $_REQUEST['page'] ?? 1;
2530 $since_id = $_REQUEST['since_id'] ?? 0;
2531 $max_id = $_REQUEST['max_id'] ?? 0;
2533 $user_id = $_REQUEST['user_id'] ?? '';
2534 $screen_name = $_REQUEST['screen_name'] ?? '';
2536 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2538 $profile_url = $user_info["url"];
2541 $start = max(0, ($page - 1) * $count);
2546 if ($box=="sentbox") {
2547 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
2548 } elseif ($box == "conversation") {
2549 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
2550 } elseif ($box == "all") {
2551 $sql_extra = "true";
2552 } elseif ($box == "inbox") {
2553 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
2557 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
2560 if ($user_id != "") {
2561 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2562 } elseif ($screen_name !="") {
2563 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
2566 $r = DBA::toArray(DBA::p(
2567 "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 ?,?",
2573 if ($verbose == "true" && !DBA::isResult($r)) {
2574 $answer = ['result' => 'error', 'message' => 'no mails available'];
2575 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
2579 foreach ($r as $item) {
2580 if ($box == "inbox" || $item['from-url'] != $profile_url) {
2581 $recipient = $user_info;
2582 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2583 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
2584 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2585 $sender = $user_info;
2588 if (isset($recipient) && isset($sender)) {
2589 $ret[] = api_format_messages($item, $recipient, $sender);
2593 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2597 * Returns the most recent direct messages sent by the user.
2599 * @param string $type Return type (atom, rss, xml, json)
2601 * @return array|string
2602 * @throws BadRequestException
2603 * @throws ForbiddenException
2604 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
2606 function api_direct_messages_sentbox($type)
2608 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2609 return api_direct_messages_box($type, "sentbox", $verbose);
2612 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
2615 * Returns the most recent direct messages sent to the user.
2617 * @param string $type Return type (atom, rss, xml, json)
2619 * @return array|string
2620 * @throws BadRequestException
2621 * @throws ForbiddenException
2622 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
2624 function api_direct_messages_inbox($type)
2626 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2627 return api_direct_messages_box($type, "inbox", $verbose);
2630 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
2634 * @param string $type Return type (atom, rss, xml, json)
2636 * @return array|string
2637 * @throws BadRequestException
2638 * @throws ForbiddenException
2640 function api_direct_messages_all($type)
2642 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2643 return api_direct_messages_box($type, "all", $verbose);
2646 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
2650 * @param string $type Return type (atom, rss, xml, json)
2652 * @return array|string
2653 * @throws BadRequestException
2654 * @throws ForbiddenException
2656 function api_direct_messages_conversation($type)
2658 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2659 return api_direct_messages_box($type, "conversation", $verbose);
2662 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
2665 * list all photos of the authenticated user
2667 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2668 * @return string|array
2669 * @throws ForbiddenException
2670 * @throws InternalServerErrorException
2672 function api_fr_photos_list($type)
2674 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2675 $uid = BaseApi::getCurrentUserID();
2677 $r = DBA::toArray(DBA::p(
2678 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
2679 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
2680 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
2681 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
2684 'image/jpeg' => 'jpg',
2685 'image/png' => 'png',
2686 'image/gif' => 'gif'
2688 $data = ['photo'=>[]];
2689 if (DBA::isResult($r)) {
2690 foreach ($r as $rr) {
2692 $photo['id'] = $rr['resource-id'];
2693 $photo['album'] = $rr['album'];
2694 $photo['filename'] = $rr['filename'];
2695 $photo['type'] = $rr['type'];
2696 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
2697 $photo['created'] = $rr['created'];
2698 $photo['edited'] = $rr['edited'];
2699 $photo['desc'] = $rr['desc'];
2701 if ($type == "xml") {
2702 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
2704 $photo['thumb'] = $thumb;
2705 $data['photo'][] = $photo;
2709 return DI::apiResponse()->formatData("photos", $type, $data);
2712 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2715 * upload a new photo or change an existing photo
2717 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2718 * @return string|array
2719 * @throws BadRequestException
2720 * @throws ForbiddenException
2721 * @throws ImagickException
2722 * @throws InternalServerErrorException
2723 * @throws NotFoundException
2725 function api_fr_photo_create_update($type)
2727 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2728 $uid = BaseApi::getCurrentUserID();
2731 $photo_id = $_REQUEST['photo_id'] ?? null;
2732 $desc = $_REQUEST['desc'] ?? null;
2733 $album = $_REQUEST['album'] ?? null;
2734 $album_new = $_REQUEST['album_new'] ?? null;
2735 $allow_cid = $_REQUEST['allow_cid'] ?? null;
2736 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
2737 $allow_gid = $_REQUEST['allow_gid'] ?? null;
2738 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
2739 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
2741 // do several checks on input parameters
2742 // we do not allow calls without album string
2743 if ($album == null) {
2744 throw new BadRequestException("no albumname specified");
2746 // if photo_id == null --> we are uploading a new photo
2747 if ($photo_id == null) {
2750 // error if no media posted in create-mode
2751 if (empty($_FILES['media'])) {
2753 throw new BadRequestException("no media data submitted");
2756 // album_new will be ignored in create-mode
2761 // check if photo is existing in databasei
2762 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
2763 throw new BadRequestException("photo not available");
2767 // checks on acl strings provided by clients
2768 $acl_input_error = false;
2769 $acl_input_error |= check_acl_input($allow_cid, $uid);
2770 $acl_input_error |= check_acl_input($deny_cid, $uid);
2771 $acl_input_error |= check_acl_input($allow_gid, $uid);
2772 $acl_input_error |= check_acl_input($deny_gid, $uid);
2773 if ($acl_input_error) {
2774 throw new BadRequestException("acl data invalid");
2776 // now let's upload the new media in create-mode
2777 if ($mode == "create") {
2778 $media = $_FILES['media'];
2779 $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);
2781 // return success of updating or error message
2782 if (!is_null($data)) {
2783 return DI::apiResponse()->formatData("photo_create", $type, $data);
2785 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
2789 // now let's do the changes in update-mode
2790 if ($mode == "update") {
2791 $updated_fields = [];
2793 if (!is_null($desc)) {
2794 $updated_fields['desc'] = $desc;
2797 if (!is_null($album_new)) {
2798 $updated_fields['album'] = $album_new;
2801 if (!is_null($allow_cid)) {
2802 $allow_cid = trim($allow_cid);
2803 $updated_fields['allow_cid'] = $allow_cid;
2806 if (!is_null($deny_cid)) {
2807 $deny_cid = trim($deny_cid);
2808 $updated_fields['deny_cid'] = $deny_cid;
2811 if (!is_null($allow_gid)) {
2812 $allow_gid = trim($allow_gid);
2813 $updated_fields['allow_gid'] = $allow_gid;
2816 if (!is_null($deny_gid)) {
2817 $deny_gid = trim($deny_gid);
2818 $updated_fields['deny_gid'] = $deny_gid;
2822 if (count($updated_fields) > 0) {
2823 $nothingtodo = false;
2824 $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
2826 $nothingtodo = true;
2829 if (!empty($_FILES['media'])) {
2830 $nothingtodo = false;
2831 $media = $_FILES['media'];
2832 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
2833 if (!is_null($data)) {
2834 return DI::apiResponse()->formatData("photo_update", $type, $data);
2838 // return success of updating or error message
2840 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
2841 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
2844 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
2845 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
2847 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
2850 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
2853 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
2854 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
2857 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
2859 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2860 * @return string|array
2861 * @throws BadRequestException
2862 * @throws ForbiddenException
2863 * @throws InternalServerErrorException
2864 * @throws NotFoundException
2866 function api_fr_photo_detail($type)
2868 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2869 $uid = BaseApi::getCurrentUserID();
2871 if (empty($_REQUEST['photo_id'])) {
2872 throw new BadRequestException("No photo id.");
2875 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
2876 $photo_id = $_REQUEST['photo_id'];
2878 // prepare json/xml output with data from database for the requested photo
2879 $data = prepare_photo_data($type, $scale, $photo_id, $uid);
2881 return DI::apiResponse()->formatData("photo_detail", $type, $data);
2884 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2887 * updates the profile image for the user (either a specified profile or the default profile)
2889 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2891 * @return string|array
2892 * @throws BadRequestException
2893 * @throws ForbiddenException
2894 * @throws ImagickException
2895 * @throws InternalServerErrorException
2896 * @throws NotFoundException
2897 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
2899 function api_account_update_profile_image($type)
2901 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2902 $uid = BaseApi::getCurrentUserID();
2905 $profile_id = $_REQUEST['profile_id'] ?? 0;
2907 // error if image data is missing
2908 if (empty($_FILES['image'])) {
2909 throw new BadRequestException("no media data submitted");
2912 // check if specified profile id is valid
2913 if ($profile_id != 0) {
2914 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
2915 // error message if specified profile id is not in database
2916 if (!DBA::isResult($profile)) {
2917 throw new BadRequestException("profile_id not available");
2919 $is_default_profile = $profile['is-default'];
2921 $is_default_profile = 1;
2924 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
2926 if (!empty($_FILES['image'])) {
2927 $media = $_FILES['image'];
2928 } elseif (!empty($_FILES['media'])) {
2929 $media = $_FILES['media'];
2931 // save new profile image
2932 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
2935 if (is_array($media['type'])) {
2936 $filetype = $media['type'][0];
2938 $filetype = $media['type'];
2940 if ($filetype == "image/jpeg") {
2942 } elseif ($filetype == "image/png") {
2945 throw new InternalServerErrorException('Unsupported filetype');
2948 // change specified profile or all profiles to the new resource-id
2949 if ($is_default_profile) {
2950 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
2951 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
2953 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
2954 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
2955 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
2958 Contact::updateSelfFromUserID($uid, true);
2960 // Update global directory in background
2961 Profile::publishUpdate($uid);
2963 // output for client
2965 return api_account_verify_credentials($type);
2967 // SaveMediaToDatabase failed for some reason
2968 throw new InternalServerErrorException("image upload failed");
2972 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
2975 * Update user profile
2977 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2979 * @return array|string
2980 * @throws BadRequestException
2981 * @throws ForbiddenException
2982 * @throws ImagickException
2983 * @throws InternalServerErrorException
2984 * @throws UnauthorizedException
2986 function api_account_update_profile($type)
2988 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2989 $uid = BaseApi::getCurrentUserID();
2991 $api_user = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2993 if (!empty($_POST['name'])) {
2994 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $uid]);
2995 DBA::update('user', ['username' => $_POST['name']], ['uid' => $uid]);
2996 Contact::update(['name' => $_POST['name']], ['uid' => $uid, 'self' => 1]);
2997 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3000 if (isset($_POST['description'])) {
3001 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $uid]);
3002 Contact::update(['about' => $_POST['description']], ['uid' => $uid, 'self' => 1]);
3003 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3006 Profile::publishUpdate($uid);
3008 return api_account_verify_credentials($type);
3011 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3014 * Return all or a specified group of the user with the containing contacts.
3016 * @param string $type Return type (atom, rss, xml, json)
3018 * @return array|string
3019 * @throws BadRequestException
3020 * @throws ForbiddenException
3021 * @throws ImagickException
3022 * @throws InternalServerErrorException
3023 * @throws UnauthorizedException
3025 function api_friendica_group_show($type)
3027 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3028 $uid = BaseApi::getCurrentUserID();
3031 $gid = $_REQUEST['gid'] ?? 0;
3033 // get data of the specified group id or all groups if not specified
3035 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
3037 // error message if specified gid is not in database
3038 if (!DBA::isResult($groups)) {
3039 throw new BadRequestException("gid not available");
3042 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
3045 // loop through all groups and retrieve all members for adding data in the user array
3047 foreach ($groups as $rr) {
3048 $members = Contact\Group::getById($rr['id']);
3051 if ($type == "xml") {
3052 $user_element = "users";
3054 foreach ($members as $member) {
3055 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
3056 $users[$k++.":user"] = $user;
3059 $user_element = "user";
3060 foreach ($members as $member) {
3061 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
3065 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
3067 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
3070 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3075 * @param string $type Return type (atom, rss, xml, json)
3077 * @return array|string
3078 * @throws BadRequestException
3079 * @throws ForbiddenException
3080 * @throws ImagickException
3081 * @throws InternalServerErrorException
3082 * @throws UnauthorizedException
3083 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
3085 function api_lists_destroy($type)
3087 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3088 $uid = BaseApi::getCurrentUserID();
3091 $gid = $_REQUEST['list_id'] ?? 0;
3093 // error if no gid specified
3095 throw new BadRequestException('gid not specified');
3098 // get data of the specified group id
3099 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
3100 // error message if specified gid is not in database
3102 throw new BadRequestException('gid not available');
3105 if (Group::remove($gid)) {
3107 'name' => $group['name'],
3108 'id' => intval($gid),
3109 'id_str' => (string) $gid,
3110 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
3113 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
3117 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
3120 * Create the specified group with the posted array of contacts.
3122 * @param string $type Return type (atom, rss, xml, json)
3124 * @return array|string
3125 * @throws BadRequestException
3126 * @throws ForbiddenException
3127 * @throws ImagickException
3128 * @throws InternalServerErrorException
3129 * @throws UnauthorizedException
3131 function api_friendica_group_create($type)
3133 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3134 $uid = BaseApi::getCurrentUserID();
3137 $name = $_REQUEST['name'] ?? '';
3138 $json = json_decode($_POST['json'], true);
3139 $users = $json['user'];
3141 $success = group_create($name, $uid, $users);
3143 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
3146 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3149 * Create a new group.
3151 * @param string $type Return type (atom, rss, xml, json)
3153 * @return array|string
3154 * @throws BadRequestException
3155 * @throws ForbiddenException
3156 * @throws ImagickException
3157 * @throws InternalServerErrorException
3158 * @throws UnauthorizedException
3159 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
3161 function api_lists_create($type)
3163 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3164 $uid = BaseApi::getCurrentUserID();
3167 $name = $_REQUEST['name'] ?? '';
3169 $success = group_create($name, $uid);
3170 if ($success['success']) {
3172 'name' => $success['name'],
3173 'id' => intval($success['gid']),
3174 'id_str' => (string) $success['gid'],
3175 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
3178 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
3182 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
3185 * Update the specified group with the posted array of contacts.
3187 * @param string $type Return type (atom, rss, xml, json)
3189 * @return array|string
3190 * @throws BadRequestException
3191 * @throws ForbiddenException
3192 * @throws ImagickException
3193 * @throws InternalServerErrorException
3194 * @throws UnauthorizedException
3196 function api_friendica_group_update($type)
3198 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3199 $uid = BaseApi::getCurrentUserID();
3202 $gid = $_REQUEST['gid'] ?? 0;
3203 $name = $_REQUEST['name'] ?? '';
3204 $json = json_decode($_POST['json'], true);
3205 $users = $json['user'];
3207 // error if no name specified
3209 throw new BadRequestException('group name not specified');
3212 // error if no gid specified
3214 throw new BadRequestException('gid not specified');
3218 $members = Contact\Group::getById($gid);
3219 foreach ($members as $member) {
3220 $cid = $member['id'];
3221 foreach ($users as $user) {
3222 $found = ($user['cid'] == $cid ? true : false);
3224 if (!isset($found) || !$found) {
3225 $gid = Group::getIdByName($uid, $name);
3226 Group::removeMember($gid, $cid);
3231 $erroraddinguser = false;
3233 foreach ($users as $user) {
3234 $cid = $user['cid'];
3236 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
3237 Group::addMember($gid, $cid);
3239 $erroraddinguser = true;
3240 $errorusers[] = $cid;
3244 // return success message incl. missing users in array
3245 $status = ($erroraddinguser ? "missing user" : "ok");
3246 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
3247 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
3250 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3253 * Update information about a group.
3255 * @param string $type Return type (atom, rss, xml, json)
3257 * @return array|string
3258 * @throws BadRequestException
3259 * @throws ForbiddenException
3260 * @throws ImagickException
3261 * @throws InternalServerErrorException
3262 * @throws UnauthorizedException
3263 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
3265 function api_lists_update($type)
3267 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3268 $uid = BaseApi::getCurrentUserID();
3271 $gid = $_REQUEST['list_id'] ?? 0;
3272 $name = $_REQUEST['name'] ?? '';
3274 // error if no gid specified
3276 throw new BadRequestException('gid not specified');
3279 // get data of the specified group id
3280 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
3281 // error message if specified gid is not in database
3283 throw new BadRequestException('gid not available');
3286 if (Group::update($gid, $name)) {
3289 'id' => intval($gid),
3290 'id_str' => (string) $gid,
3291 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
3294 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
3298 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
3301 * Set notification as seen and returns associated item (if possible)
3303 * POST request with 'id' param as notification id
3305 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3306 * @return string|array
3307 * @throws BadRequestException
3308 * @throws ForbiddenException
3309 * @throws ImagickException
3310 * @throws InternalServerErrorException
3311 * @throws UnauthorizedException
3313 function api_friendica_notification_seen($type)
3315 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3316 $uid = BaseApi::getCurrentUserID();
3318 if (DI::args()->getArgc() !== 4) {
3319 throw new BadRequestException('Invalid argument count');
3322 $id = intval($_REQUEST['id'] ?? 0);
3325 $Notify = DI::notify()->selectOneById($id);
3326 if ($Notify->uid !== $uid) {
3327 throw new NotFoundException();
3330 if ($Notify->uriId) {
3331 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
3335 DI::notify()->save($Notify);
3337 if ($Notify->otype === Notification\ObjectType::ITEM) {
3338 $item = Post::selectFirstForUser($uid, [], ['id' => $Notify->iid, 'uid' => $uid]);
3339 if (DBA::isResult($item)) {
3340 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
3342 // we found the item, return it to the user
3343 $ret = [DI::twitterStatus()->createFromUriId($item['uri-id'], $item['uid'], $include_entities)->toArray()];
3344 $data = ['status' => $ret];
3345 return DI::apiResponse()->formatData('status', $type, $data);
3347 // the item can't be found, but we set the notification as seen, so we count this as a success
3350 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
3351 } catch (NotFoundException $e) {
3352 throw new BadRequestException('Invalid argument', $e);
3353 } catch (Exception $e) {
3354 throw new InternalServerErrorException('Internal Server exception', $e);
3358 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3361 * search for direct_messages containing a searchstring through api
3363 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3364 * @param string $box
3365 * @return string|array (success: success=true if found and search_result contains found messages,
3366 * success=false if nothing was found, search_result='nothing found',
3367 * error: result=error with error message)
3368 * @throws BadRequestException
3369 * @throws ForbiddenException
3370 * @throws ImagickException
3371 * @throws InternalServerErrorException
3372 * @throws UnauthorizedException
3374 function api_friendica_direct_messages_search($type, $box = "")
3376 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3377 $uid = BaseApi::getCurrentUserID();
3380 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
3381 $searchstring = $_REQUEST['searchstring'] ?? '';
3383 // error if no searchstring specified
3384 if ($searchstring == "") {
3385 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
3386 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
3389 // get data for the specified searchstring
3390 $r = DBA::toArray(DBA::p(
3391 "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",
3393 '%'.$searchstring.'%'
3396 $profile_url = $user_info["url"];
3398 // message if nothing was found
3399 if (!DBA::isResult($r)) {
3400 $success = ['success' => false, 'search_results' => 'problem with query'];
3401 } elseif (count($r) == 0) {
3402 $success = ['success' => false, 'search_results' => 'nothing found'];
3405 foreach ($r as $item) {
3406 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3407 $recipient = $user_info;
3408 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
3409 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3410 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
3411 $sender = $user_info;
3414 if (isset($recipient) && isset($sender)) {
3415 $ret[] = api_format_messages($item, $recipient, $sender);
3418 $success = ['success' => true, 'search_results' => $ret];
3421 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
3424 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);