3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\System;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Group;
36 use Friendica\Model\Item;
37 use Friendica\Model\Mail;
38 use Friendica\Model\Notification;
39 use Friendica\Model\Photo;
40 use Friendica\Model\Post;
41 use Friendica\Model\Profile;
42 use Friendica\Model\User;
43 use Friendica\Module\BaseApi;
44 use Friendica\Network\HTTPException;
45 use Friendica\Network\HTTPException\BadRequestException;
46 use Friendica\Network\HTTPException\ForbiddenException;
47 use Friendica\Network\HTTPException\InternalServerErrorException;
48 use Friendica\Network\HTTPException\NotFoundException;
49 use Friendica\Network\HTTPException\TooManyRequestsException;
50 use Friendica\Network\HTTPException\UnauthorizedException;
51 use Friendica\Object\Image;
52 use Friendica\Security\BasicAuth;
53 use Friendica\Util\DateTimeFormat;
54 use Friendica\Util\Images;
55 use Friendica\Util\Network;
56 use Friendica\Util\Strings;
58 require_once __DIR__ . '/../mod/item.php';
59 require_once __DIR__ . '/../mod/wall_upload.php';
61 define('API_METHOD_ANY', '*');
62 define('API_METHOD_GET', 'GET');
63 define('API_METHOD_POST', 'POST,PUT');
64 define('API_METHOD_DELETE', 'POST,DELETE');
66 define('API_LOG_PREFIX', 'API {action} - ');
71 * Register a function to be the endpoint for defined API path.
73 * @param string $path API URL path, relative to DI::baseUrl()
74 * @param string $func Function name to call on path request
75 * @param bool $auth API need logged user
76 * @param string $method HTTP method reqiured to call this endpoint.
77 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
78 * Default to API_METHOD_ANY
80 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
90 // Workaround for hotot
91 $path = str_replace("api/", "api/1.1/", $path);
101 * Main API entry point
103 * Authenticate user, call registered API function, set HTTP headers
106 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
107 * @return string|array API call result
110 function api_call(App $a, App\Arguments $args = null)
119 if (strpos($args->getCommand(), ".xml") > 0) {
122 if (strpos($args->getCommand(), ".json") > 0) {
125 if (strpos($args->getCommand(), ".rss") > 0) {
128 if (strpos($args->getCommand(), ".atom") > 0) {
133 foreach ($API as $p => $info) {
134 if (strpos($args->getCommand(), $p) === 0) {
135 if (!empty($info['auth']) && BaseApi::getCurrentUserID() === false) {
136 BasicAuth::getCurrentUserID(true);
137 Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
140 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
142 $stamp = microtime(true);
143 $return = call_user_func($info['func'], $type);
144 $duration = floatval(microtime(true) - $stamp);
146 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
148 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
150 if (false === $return) {
152 * api function returned false withour throw an
153 * exception. This should not happend, throw a 500
155 throw new InternalServerErrorException();
160 header("Content-Type: text/xml");
163 header("Content-Type: application/json");
164 if (!empty($return)) {
165 $json = json_encode(end($return));
166 if (!empty($_GET['callback'])) {
167 $json = $_GET['callback'] . "(" . $json . ")";
173 header("Content-Type: application/rss+xml");
174 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
177 header("Content-Type: application/atom+xml");
178 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
185 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
186 throw new NotFoundException();
187 } catch (HTTPException $e) {
188 Logger::notice(API_LOG_PREFIX . 'got exception', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString(), 'error' => $e]);
189 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
196 * @param array $recipient
197 * @param array $sender
200 * @throws InternalServerErrorException
202 function api_format_messages($item, $recipient, $sender)
204 // standard meta information
207 'sender_id' => $sender['id'],
209 'recipient_id' => $recipient['id'],
210 'created_at' => DateTimeFormat::utc($item['created'] ?? 'now', DateTimeFormat::API),
211 'sender_screen_name' => $sender['screen_name'],
212 'recipient_screen_name' => $recipient['screen_name'],
214 'recipient' => $recipient,
216 'friendica_seen' => $item['seen'] ?? 0,
217 'friendica_parent_uri' => $item['parent-uri'] ?? '',
220 // "uid" is only needed for some internal stuff, so remove it from here
221 if (isset($ret['sender']['uid'])) {
222 unset($ret['sender']['uid']);
224 if (isset($ret['recipient']['uid'])) {
225 unset($ret['recipient']['uid']);
228 //don't send title to regular StatusNET requests to avoid confusing these apps
229 if (!empty($_GET['getText'])) {
230 $ret['title'] = $item['title'];
231 if ($_GET['getText'] == 'html') {
232 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
233 } elseif ($_GET['getText'] == 'plain') {
234 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
237 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
239 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
240 unset($ret['sender']);
241 unset($ret['recipient']);
249 * @param string $acl_string
254 function check_acl_input($acl_string, $uid)
256 if (empty($acl_string)) {
260 $contact_not_found = false;
262 // split <x><y><z> into array of cid's
263 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
265 // check for each cid if it is available on server
266 $cid_array = $array[0];
267 foreach ($cid_array as $cid) {
268 $cid = str_replace("<", "", $cid);
269 $cid = str_replace(">", "", $cid);
270 $condition = ['id' => $cid, 'uid' => $uid];
271 $contact_not_found |= !DBA::exists('contact', $condition);
273 return $contact_not_found;
277 * @param string $mediatype
278 * @param array $media
279 * @param string $type
280 * @param string $album
281 * @param string $allow_cid
282 * @param string $deny_cid
283 * @param string $allow_gid
284 * @param string $deny_gid
285 * @param string $desc
286 * @param integer $phototype
287 * @param boolean $visibility
288 * @param string $photo_id
291 * @throws BadRequestException
292 * @throws ForbiddenException
293 * @throws ImagickException
294 * @throws InternalServerErrorException
295 * @throws NotFoundException
296 * @throws UnauthorizedException
298 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype, $visibility, $photo_id, $uid)
306 if (is_array($media)) {
307 if (is_array($media['tmp_name'])) {
308 $src = $media['tmp_name'][0];
310 $src = $media['tmp_name'];
312 if (is_array($media['name'])) {
313 $filename = basename($media['name'][0]);
315 $filename = basename($media['name']);
317 if (is_array($media['size'])) {
318 $filesize = intval($media['size'][0]);
320 $filesize = intval($media['size']);
322 if (is_array($media['type'])) {
323 $filetype = $media['type'][0];
325 $filetype = $media['type'];
329 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
332 "File upload src: " . $src . " - filename: " . $filename .
333 " - size: " . $filesize . " - type: " . $filetype);
335 // check if there was a php upload error
336 if ($filesize == 0 && $media['error'] == 1) {
337 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
339 // check against max upload size within Friendica instance
340 $maximagesize = DI::config()->get('system', 'maximagesize');
341 if ($maximagesize && ($filesize > $maximagesize)) {
342 $formattedBytes = Strings::formatBytes($maximagesize);
343 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
346 // create Photo instance with the data of the image
347 $imagedata = @file_get_contents($src);
348 $Image = new Image($imagedata, $filetype);
349 if (!$Image->isValid()) {
350 throw new InternalServerErrorException("unable to process image data");
353 // check orientation of image
354 $Image->orient($src);
357 // check max length of images on server
358 $max_length = DI::config()->get('system', 'max_image_length');
359 if ($max_length > 0) {
360 $Image->scaleDown($max_length);
361 logger::info("File upload: Scaling picture to new size " . $max_length);
363 $width = $Image->getWidth();
364 $height = $Image->getHeight();
366 // create a new resource-id if not already provided
367 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
369 if ($mediatype == "photo") {
370 // upload normal image (scales 0, 1, 2)
371 logger::info("photo upload: starting new photo upload");
373 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
375 logger::notice("photo upload: image upload with scale 0 (original size) failed");
377 if ($width > 640 || $height > 640) {
378 $Image->scaleDown(640);
379 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
381 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
385 if ($width > 320 || $height > 320) {
386 $Image->scaleDown(320);
387 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
389 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
392 logger::info("photo upload: new photo upload ended");
393 } elseif ($mediatype == "profileimage") {
394 // upload profile image (scales 4, 5, 6)
395 logger::info("photo upload: starting new profile image upload");
397 if ($width > 300 || $height > 300) {
398 $Image->scaleDown(300);
399 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
401 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
405 if ($width > 80 || $height > 80) {
406 $Image->scaleDown(80);
407 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
409 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
413 if ($width > 48 || $height > 48) {
414 $Image->scaleDown(48);
415 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
417 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
420 $Image->__destruct();
421 logger::info("photo upload: new profile image upload ended");
425 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
426 if ($photo_id == null && $mediatype == "photo") {
427 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid);
429 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
430 return prepare_photo_data($type, false, $resource_id, $uid);
432 throw new InternalServerErrorException("image upload failed");
438 * @param string $hash
439 * @param string $allow_cid
440 * @param string $deny_cid
441 * @param string $allow_gid
442 * @param string $deny_gid
443 * @param string $filetype
444 * @param boolean $visibility
446 * @throws InternalServerErrorException
448 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid)
450 // get data about the api authenticated user
451 $uri = Item::newURI(intval($uid));
452 $owner_record = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
455 $arr['guid'] = System::createUUID();
456 $arr['uid'] = intval($uid);
458 $arr['type'] = 'photo';
460 $arr['resource-id'] = $hash;
461 $arr['contact-id'] = $owner_record['id'];
462 $arr['owner-name'] = $owner_record['name'];
463 $arr['owner-link'] = $owner_record['url'];
464 $arr['owner-avatar'] = $owner_record['thumb'];
465 $arr['author-name'] = $owner_record['name'];
466 $arr['author-link'] = $owner_record['url'];
467 $arr['author-avatar'] = $owner_record['thumb'];
469 $arr['allow_cid'] = $allow_cid;
470 $arr['allow_gid'] = $allow_gid;
471 $arr['deny_cid'] = $deny_cid;
472 $arr['deny_gid'] = $deny_gid;
473 $arr['visible'] = $visibility;
477 'image/jpeg' => 'jpg',
478 'image/png' => 'png',
482 // adds link to the thumbnail scale photo
483 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
484 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
487 // do the magic for storing the item in the database and trigger the federation to other contacts
493 * @param string $type
495 * @param string $photo_id
498 * @throws BadRequestException
499 * @throws ForbiddenException
500 * @throws ImagickException
501 * @throws InternalServerErrorException
502 * @throws NotFoundException
503 * @throws UnauthorizedException
505 function prepare_photo_data($type, $scale, $photo_id, $uid)
507 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
508 $data_sql = ($scale === false ? "" : "data, ");
510 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
511 // clients needs to convert this in their way for further processing
512 $r = DBA::toArray(DBA::p(
513 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
514 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
515 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
516 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
517 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
518 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
524 'image/jpeg' => 'jpg',
525 'image/png' => 'png',
529 // prepare output data for photo
530 if (DBA::isResult($r)) {
531 $data = ['photo' => $r[0]];
532 $data['photo']['id'] = $data['photo']['resource-id'];
533 if ($scale !== false) {
534 $data['photo']['data'] = base64_encode($data['photo']['data']);
536 unset($data['photo']['datasize']); //needed only with scale param
538 if ($type == "xml") {
539 $data['photo']['links'] = [];
540 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
541 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
543 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
546 $data['photo']['link'] = [];
547 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
549 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
550 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
554 unset($data['photo']['resource-id']);
555 unset($data['photo']['minscale']);
556 unset($data['photo']['maxscale']);
558 throw new NotFoundException();
561 // retrieve item element for getting activities (like, dislike etc.) related to photo
562 $condition = ['uid' => $uid, 'resource-id' => $photo_id];
563 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
564 if (!DBA::isResult($item)) {
565 throw new NotFoundException('Photo-related item not found.');
568 $data['photo']['friendica_activities'] = DI::friendicaActivities()->createFromUriId($item['uri-id'], $item['uid'], $type);
570 // retrieve comments on photo
571 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
572 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
574 $statuses = Post::selectForUser($uid, [], $condition);
576 // prepare output of comments
578 while ($status = DBA::fetch($statuses)) {
579 $commentData[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'])->toArray();
581 DBA::close($statuses);
584 if ($type == "xml") {
586 foreach ($commentData as $comment) {
587 $comments[$k++ . ":comment"] = $comment;
590 foreach ($commentData as $comment) {
591 $comments[] = $comment;
594 $data['photo']['friendica_comments'] = $comments;
596 // include info if rights on photo and rights on item are mismatching
597 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
598 $data['photo']['deny_cid'] != $item['deny_cid'] ||
599 $data['photo']['allow_gid'] != $item['allow_gid'] ||
600 $data['photo']['deny_gid'] != $item['deny_gid'];
601 $data['photo']['rights_mismatch'] = $rights_mismatch;
608 * @param string $text
611 * @throws InternalServerErrorException
613 function api_clean_plain_items($text)
615 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
617 $text = BBCode::cleanPictureLinks($text);
618 $URLSearchString = "^\[\]";
620 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
622 if ($include_entities == "true") {
623 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
626 // Simplify "attachment" element
627 $text = BBCode::removeAttachment($text);
633 * Add a new group to the database.
635 * @param string $name Group name
636 * @param int $uid User ID
637 * @param array $users List of users to add to the group
640 * @throws BadRequestException
642 function group_create($name, $uid, $users = [])
644 // error if no name specified
646 throw new BadRequestException('group name not specified');
649 // error message if specified group name already exists
650 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
651 throw new BadRequestException('group name already exists');
654 // Check if the group needs to be reactivated
655 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
656 $reactivate_group = true;
660 $ret = Group::create($uid, $name);
662 $gid = Group::getIdByName($uid, $name);
664 throw new BadRequestException('other API error');
668 $erroraddinguser = false;
670 foreach ($users as $user) {
672 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
673 Group::addMember($gid, $cid);
675 $erroraddinguser = true;
676 $errorusers[] = $cid;
680 // return success message incl. missing users in array
681 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
683 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
691 * Deprecated function to upload media.
693 * @param string $type Return type (atom, rss, xml, json)
695 * @return array|string
696 * @throws BadRequestException
697 * @throws ForbiddenException
698 * @throws ImagickException
699 * @throws InternalServerErrorException
700 * @throws UnauthorizedException
702 function api_statuses_mediap($type)
704 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
705 $uid = BaseApi::getCurrentUserID();
709 $_REQUEST['profile_uid'] = $uid;
710 $_REQUEST['api_source'] = true;
711 $txt = $_REQUEST['status'] ?? '';
713 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
714 $txt = HTML::toBBCodeVideo($txt);
715 $config = HTMLPurifier_Config::createDefault();
716 $config->set('Cache.DefinitionImpl', null);
717 $purifier = new HTMLPurifier($config);
718 $txt = $purifier->purify($txt);
720 $txt = HTML::toBBCode($txt);
722 $picture = wall_upload_post($a, false);
724 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
725 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
726 $item_id = item_post($a);
728 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
730 // output the post that we just posted.
731 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
732 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
735 /// @TODO move this to top of file or somewhere better!
736 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
739 * Updates the user’s current status.
741 * @param string $type Return type (atom, rss, xml, json)
743 * @return array|string
744 * @throws BadRequestException
745 * @throws ForbiddenException
746 * @throws ImagickException
747 * @throws InternalServerErrorException
748 * @throws TooManyRequestsException
749 * @throws UnauthorizedException
750 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
752 function api_statuses_update($type)
754 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
755 $uid = BaseApi::getCurrentUserID();
759 // convert $_POST array items to the form we use for web posts.
760 if (!empty($_REQUEST['htmlstatus'])) {
761 $txt = $_REQUEST['htmlstatus'];
762 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
763 $txt = HTML::toBBCodeVideo($txt);
765 $config = HTMLPurifier_Config::createDefault();
766 $config->set('Cache.DefinitionImpl', null);
768 $purifier = new HTMLPurifier($config);
769 $txt = $purifier->purify($txt);
771 $_REQUEST['body'] = HTML::toBBCode($txt);
774 $_REQUEST['body'] = $_REQUEST['status'] ?? null;
777 $_REQUEST['title'] = $_REQUEST['title'] ?? null;
779 $parent = $_REQUEST['in_reply_to_status_id'] ?? null;
781 // Twidere sends "-1" if it is no reply ...
786 if (ctype_digit($parent)) {
787 $_REQUEST['parent'] = $parent;
789 $_REQUEST['parent_uri'] = $parent;
792 if (!empty($_REQUEST['lat']) && !empty($_REQUEST['long'])) {
793 $_REQUEST['coord'] = sprintf("%s %s", $_REQUEST['lat'], $_REQUEST['long']);
795 $_REQUEST['profile_uid'] = $uid;
798 // Check for throttling (maximum posts per day, week and month)
799 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
800 if ($throttle_day > 0) {
801 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
803 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
804 $posts_day = Post::count($condition);
806 if ($posts_day > $throttle_day) {
807 logger::info('Daily posting limit reached for user ' . $uid);
808 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
809 throw new TooManyRequestsException(DI::l10n()->tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
813 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
814 if ($throttle_week > 0) {
815 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
817 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
818 $posts_week = Post::count($condition);
820 if ($posts_week > $throttle_week) {
821 logger::info('Weekly posting limit reached for user ' . $uid);
822 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
823 throw new TooManyRequestsException(DI::l10n()->tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
827 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
828 if ($throttle_month > 0) {
829 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
831 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
832 $posts_month = Post::count($condition);
834 if ($posts_month > $throttle_month) {
835 logger::info('Monthly posting limit reached for user ' . $uid);
836 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
837 throw new TooManyRequestsException(DI::l10n()->t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
842 if (!empty($_REQUEST['media_ids'])) {
843 $ids = explode(',', $_REQUEST['media_ids']);
844 } elseif (!empty($_FILES['media'])) {
845 // upload the image if we have one
846 $picture = wall_upload_post($a, false);
847 if (is_array($picture)) {
848 $ids[] = $picture['id'];
856 foreach ($ids as $id) {
857 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
858 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
859 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
860 ORDER BY `photo`.`width` DESC LIMIT 2", $id, $uid));
862 if (!empty($media)) {
863 $ressources[] = $media[0]['resource-id'];
864 $phototypes = Images::supportedTypes();
865 $ext = $phototypes[$media[0]['type']];
867 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
868 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
869 'size' => $media[0]['datasize'],
870 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
871 'description' => $media[0]['desc'] ?? '',
872 'width' => $media[0]['width'],
873 'height' => $media[0]['height']];
875 if (count($media) > 1) {
876 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
877 $attachment['preview-width'] = $media[1]['width'];
878 $attachment['preview-height'] = $media[1]['height'];
880 $attachments[] = $attachment;
884 // We have to avoid that the post is rejected because of an empty body
885 if (empty($_REQUEST['body'])) {
886 $_REQUEST['body'] = '[hr]';
890 if (!empty($attachments)) {
891 $_REQUEST['attachments'] = $attachments;
894 // set this so that the item_post() function is quiet and doesn't redirect or emit json
896 $_REQUEST['api_source'] = true;
898 if (empty($_REQUEST['source'])) {
899 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
902 // call out normal post function
903 $item_id = item_post($a);
905 if (!empty($ressources) && !empty($item_id)) {
906 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
907 foreach ($ressources as $ressource) {
908 Photo::setPermissionForRessource($ressource, $uid, $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
912 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
914 // output the post that we just posted.
915 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
916 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
919 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
920 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
923 * Uploads an image to Friendica.
926 * @throws BadRequestException
927 * @throws ForbiddenException
928 * @throws ImagickException
929 * @throws InternalServerErrorException
930 * @throws UnauthorizedException
931 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
933 function api_media_upload()
935 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
937 if (empty($_FILES['media'])) {
939 throw new BadRequestException("No media.");
942 $media = wall_upload_post(DI::app(), false);
945 throw new InternalServerErrorException();
949 $returndata["media_id"] = $media["id"];
950 $returndata["media_id_string"] = (string)$media["id"];
951 $returndata["size"] = $media["size"];
952 $returndata["image"] = ["w" => $media["width"],
953 "h" => $media["height"],
954 "image_type" => $media["type"],
955 "friendica_preview_url" => $media["preview"]];
957 Logger::info('Media uploaded', ['return' => $returndata]);
959 return ["media" => $returndata];
962 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
965 * Updates media meta data (picture descriptions)
967 * @param string $type Return type (atom, rss, xml, json)
969 * @return array|string
970 * @throws BadRequestException
971 * @throws ForbiddenException
972 * @throws ImagickException
973 * @throws InternalServerErrorException
974 * @throws TooManyRequestsException
975 * @throws UnauthorizedException
976 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
978 * @todo Compare the corresponding Twitter function for correct return values
980 function api_media_metadata_create($type)
982 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
983 $uid = BaseApi::getCurrentUserID();
985 $postdata = Network::postdata();
987 if (empty($postdata)) {
988 throw new BadRequestException("No post data");
991 $data = json_decode($postdata, true);
993 throw new BadRequestException("Invalid post data");
996 if (empty($data['media_id']) || empty($data['alt_text'])) {
997 throw new BadRequestException("Missing post data values");
1000 if (empty($data['alt_text']['text'])) {
1001 throw new BadRequestException("No alt text.");
1004 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1006 $condition = ['id' => $data['media_id'], 'uid' => $uid];
1007 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1008 if (!DBA::isResult($photo)) {
1009 throw new BadRequestException("Metadata not found.");
1012 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1015 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1020 * @param string $type Return type (atom, rss, xml, json)
1022 * @return array|string
1023 * @throws BadRequestException
1024 * @throws ForbiddenException
1025 * @throws ImagickException
1026 * @throws InternalServerErrorException
1027 * @throws UnauthorizedException
1028 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1030 function api_statuses_repeat($type)
1032 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1033 $uid = BaseApi::getCurrentUserID();
1036 $id = intval(DI::args()->getArgv()[3] ?? 0);
1039 $id = intval($_REQUEST['id'] ?? 0);
1044 $id = intval(DI::args()->getArgv()[4] ?? 0);
1047 logger::notice('API: api_statuses_repeat: ' . $id);
1049 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1050 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1052 if (DBA::isResult($item) && !empty($item['body'])) {
1053 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1054 if (!Item::performActivity($id, 'announce', $uid)) {
1055 throw new InternalServerErrorException();
1060 if (strpos($item['body'], "[/share]") !== false) {
1061 $pos = strpos($item['body'], "[share");
1062 $post = substr($item['body'], $pos);
1064 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1066 if (!empty($item['title'])) {
1067 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1070 $post .= $item['body'];
1071 $post .= "[/share]";
1073 $_REQUEST['body'] = $post;
1074 $_REQUEST['profile_uid'] = $uid;
1075 $_REQUEST['api_source'] = true;
1077 if (empty($_REQUEST['source'])) {
1078 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
1081 $item_id = item_post(DI::app());
1084 throw new ForbiddenException();
1087 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1089 // output the post that we just posted.
1090 $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
1091 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
1094 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1097 * Star/unstar an item.
1098 * param: id : id of the item
1100 * @param string $type Return type (atom, rss, xml, json)
1102 * @return array|string
1103 * @throws BadRequestException
1104 * @throws ForbiddenException
1105 * @throws ImagickException
1106 * @throws InternalServerErrorException
1107 * @throws UnauthorizedException
1108 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1110 function api_favorites_create_destroy($type)
1112 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1113 $uid = BaseApi::getCurrentUserID();
1115 // for versioned api.
1116 /// @TODO We need a better global soluton
1117 $action_argv_id = 2;
1118 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1119 $action_argv_id = 3;
1122 if (DI::args()->getArgc() <= $action_argv_id) {
1123 throw new BadRequestException("Invalid request.");
1125 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1126 if (DI::args()->getArgc() == $action_argv_id + 2) {
1127 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1129 $itemid = intval($_REQUEST['id'] ?? 0);
1132 $item = Post::selectFirstForUser($uid, [], ['id' => $itemid, 'uid' => $uid]);
1134 if (!DBA::isResult($item)) {
1135 throw new BadRequestException("Invalid item.");
1140 $item['starred'] = 1;
1143 $item['starred'] = 0;
1146 throw new BadRequestException("Invalid action ".$action);
1149 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1152 throw new InternalServerErrorException("DB error");
1155 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1157 $ret = DI::twitterStatus()->createFromUriId($item['uri-id'], $item['uid'], $include_entities)->toArray();
1159 return DI::apiResponse()->formatData("status", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1162 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1163 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1166 * Returns all lists the user subscribes to.
1168 * @param string $type Return type (atom, rss, xml, json)
1170 * @return array|string
1171 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
1173 function api_lists_list($type)
1176 /// @TODO $ret is not filled here?
1177 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
1180 api_register_func('api/lists/list', 'api_lists_list', true);
1181 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
1184 * Returns all groups the user owns.
1186 * @param string $type Return type (atom, rss, xml, json)
1188 * @return array|string
1189 * @throws BadRequestException
1190 * @throws ForbiddenException
1191 * @throws ImagickException
1192 * @throws InternalServerErrorException
1193 * @throws UnauthorizedException
1194 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
1196 function api_lists_ownerships($type)
1198 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1199 $uid = BaseApi::getCurrentUserID();
1202 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1204 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
1206 // loop through all groups
1208 foreach ($groups as $group) {
1209 if ($group['visible']) {
1215 'name' => $group['name'],
1216 'id' => intval($group['id']),
1217 'id_str' => (string) $group['id'],
1218 'user' => $user_info,
1222 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
1225 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
1228 * Returns either the friends of the follower list
1230 * Considers friends and followers lists to be private and won't return
1231 * anything if any user_id parameter is passed.
1233 * @param string $qtype Either "friends" or "followers"
1234 * @return boolean|array
1235 * @throws BadRequestException
1236 * @throws ForbiddenException
1237 * @throws ImagickException
1238 * @throws InternalServerErrorException
1239 * @throws UnauthorizedException
1241 function api_statuses_f($qtype)
1243 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1244 $uid = BaseApi::getCurrentUserID();
1247 $count = $_GET['count'] ?? 20;
1248 $page = $_GET['page'] ?? 1;
1250 $start = max(0, ($page - 1) * $count);
1252 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
1253 /* this is to stop Hotot to load friends multiple times
1254 * I'm not sure if I'm missing return something or
1255 * is a bug in hotot. Workaround, meantime
1259 return array('$users' => $ret);*/
1264 if ($qtype == 'friends') {
1265 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
1266 } elseif ($qtype == 'followers') {
1267 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
1270 if ($qtype == 'blocks') {
1271 $sql_filter = 'AND `blocked` AND NOT `pending`';
1272 } elseif ($qtype == 'incoming') {
1273 $sql_filter = 'AND `pending`';
1275 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
1278 // @todo This query most likely can be replaced with a Contact::select...
1279 $r = DBA::toArray(DBA::p(
1294 foreach ($r as $cid) {
1295 $user = DI::twitterUser()->createFromContactId($cid['id'], $uid, false)->toArray();
1296 // "uid" is only needed for some internal stuff, so remove it from here
1297 unset($user['uid']);
1304 return ['user' => $ret];
1308 * Returns the list of friends of the provided user
1310 * @deprecated By Twitter API in favor of friends/list
1312 * @param string $type Either "json" or "xml"
1313 * @return boolean|string|array
1314 * @throws BadRequestException
1315 * @throws ForbiddenException
1317 function api_statuses_friends($type)
1319 $data = api_statuses_f("friends");
1320 if ($data === false) {
1323 return DI::apiResponse()->formatData("users", $type, $data);
1326 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
1329 * Returns the list of followers of the provided user
1331 * @deprecated By Twitter API in favor of friends/list
1333 * @param string $type Either "json" or "xml"
1334 * @return boolean|string|array
1335 * @throws BadRequestException
1336 * @throws ForbiddenException
1338 function api_statuses_followers($type)
1340 $data = api_statuses_f("followers");
1341 if ($data === false) {
1344 return DI::apiResponse()->formatData("users", $type, $data);
1347 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
1350 * Returns the list of blocked users
1352 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
1354 * @param string $type Either "json" or "xml"
1356 * @return boolean|string|array
1357 * @throws BadRequestException
1358 * @throws ForbiddenException
1360 function api_blocks_list($type)
1362 $data = api_statuses_f('blocks');
1363 if ($data === false) {
1366 return DI::apiResponse()->formatData("users", $type, $data);
1369 api_register_func('api/blocks/list', 'api_blocks_list', true);
1372 * Returns the list of pending users IDs
1374 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
1376 * @param string $type Either "json" or "xml"
1378 * @return boolean|string|array
1379 * @throws BadRequestException
1380 * @throws ForbiddenException
1382 function api_friendships_incoming($type)
1384 $data = api_statuses_f('incoming');
1385 if ($data === false) {
1390 foreach ($data['user'] as $user) {
1391 $ids[] = $user['id'];
1394 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
1397 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
1400 * Sends a new direct message.
1402 * @param string $type Return type (atom, rss, xml, json)
1404 * @return array|string
1405 * @throws BadRequestException
1406 * @throws ForbiddenException
1407 * @throws ImagickException
1408 * @throws InternalServerErrorException
1409 * @throws NotFoundException
1410 * @throws UnauthorizedException
1411 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
1413 function api_direct_messages_new($type)
1415 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1416 $uid = BaseApi::getCurrentUserID();
1418 if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
1422 $sender = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1424 $cid = BaseApi::getContactIDForSearchterm($_POST['screen_name'] ?? '', $_POST['user_id'] ?? 0, $uid);
1426 throw new NotFoundException('Recipient not found');
1430 if (!empty($_REQUEST['replyto'])) {
1431 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
1432 $replyto = $mail['parent-uri'];
1433 $sub = $mail['title'];
1435 if (!empty($_REQUEST['title'])) {
1436 $sub = $_REQUEST['title'];
1438 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
1442 $cdata = Contact::getPublicAndUserContactID($cid, $uid);
1444 $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
1447 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
1448 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid, true)->toArray(), $sender);
1450 $ret = ["error" => $id];
1453 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
1456 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
1459 * delete a direct_message from mail table through api
1461 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1462 * @return string|array
1463 * @throws BadRequestException
1464 * @throws ForbiddenException
1465 * @throws ImagickException
1466 * @throws InternalServerErrorException
1467 * @throws UnauthorizedException
1468 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
1470 function api_direct_messages_destroy($type)
1472 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1473 $uid = BaseApi::getCurrentUserID();
1476 $id = $_REQUEST['id'] ?? 0;
1478 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
1479 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
1480 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
1482 // error if no id or parenturi specified (for clients posting parent-uri as well)
1483 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
1484 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
1485 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
1488 // BadRequestException if no id specified (for clients using Twitter API)
1490 throw new BadRequestException('Message id not specified');
1493 // add parent-uri to sql command if specified by calling app
1494 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
1496 // error message if specified id is not in database
1497 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
1498 if ($verbose == "true") {
1499 $answer = ['result' => 'error', 'message' => 'message id not in database'];
1500 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
1502 /// @todo BadRequestException ok for Twitter API clients?
1503 throw new BadRequestException('message id not in database');
1507 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
1509 if ($verbose == "true") {
1512 $answer = ['result' => 'ok', 'message' => 'message deleted'];
1513 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
1515 $answer = ['result' => 'error', 'message' => 'unknown error'];
1516 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
1519 /// @todo return JSON data like Twitter API not yet implemented
1522 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
1527 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1528 * @return string|array
1529 * @throws HTTPException\BadRequestException
1530 * @throws HTTPException\ExpectationFailedException
1531 * @throws HTTPException\ForbiddenException
1532 * @throws HTTPException\InternalServerErrorException
1533 * @throws HTTPException\NotFoundException
1534 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
1536 function api_friendships_destroy($type)
1538 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1539 $uid = BaseApi::getCurrentUserID();
1541 $owner = User::getOwnerDataById($uid);
1543 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
1544 throw new HTTPException\NotFoundException('Error Processing Request');
1547 $contact_id = $_REQUEST['user_id'] ?? 0;
1549 if (empty($contact_id)) {
1550 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
1551 throw new HTTPException\BadRequestException('no user_id specified');
1554 // Get Contact by given id
1555 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
1557 if(!DBA::isResult($contact)) {
1558 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
1559 throw new HTTPException\NotFoundException('no contact found to given ID');
1562 $url = $contact['url'];
1564 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
1565 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
1566 Strings::normaliseLink($url), $url];
1567 $contact = DBA::selectFirst('contact', [], $condition);
1569 if (!DBA::isResult($contact)) {
1570 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
1571 throw new HTTPException\NotFoundException('Not following Contact');
1575 $result = Contact::terminateFriendship($owner, $contact);
1577 if ($result === null) {
1578 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
1579 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
1582 if ($result === false) {
1583 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
1585 } catch (Exception $e) {
1586 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
1587 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
1590 // "uid" is only needed for some internal stuff, so remove it from here
1591 unset($contact['uid']);
1593 // Set screen_name since Twidere requests it
1594 $contact['screen_name'] = $contact['nick'];
1596 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
1599 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
1603 * @param string $type Return type (atom, rss, xml, json)
1604 * @param string $box
1605 * @param string $verbose
1607 * @return array|string
1608 * @throws BadRequestException
1609 * @throws ForbiddenException
1610 * @throws ImagickException
1611 * @throws InternalServerErrorException
1612 * @throws UnauthorizedException
1614 function api_direct_messages_box($type, $box, $verbose)
1616 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1617 $uid = BaseApi::getCurrentUserID();
1620 $count = $_GET['count'] ?? 20;
1621 $page = $_REQUEST['page'] ?? 1;
1623 $since_id = $_REQUEST['since_id'] ?? 0;
1624 $max_id = $_REQUEST['max_id'] ?? 0;
1626 $user_id = $_REQUEST['user_id'] ?? '';
1627 $screen_name = $_REQUEST['screen_name'] ?? '';
1629 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1631 $profile_url = $user_info["url"];
1634 $start = max(0, ($page - 1) * $count);
1639 if ($box=="sentbox") {
1640 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
1641 } elseif ($box == "conversation") {
1642 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
1643 } elseif ($box == "all") {
1644 $sql_extra = "true";
1645 } elseif ($box == "inbox") {
1646 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
1650 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
1653 if ($user_id != "") {
1654 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
1655 } elseif ($screen_name !="") {
1656 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
1659 $r = DBA::toArray(DBA::p(
1660 "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 ?,?",
1666 if ($verbose == "true" && !DBA::isResult($r)) {
1667 $answer = ['result' => 'error', 'message' => 'no mails available'];
1668 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
1672 foreach ($r as $item) {
1673 if ($box == "inbox" || $item['from-url'] != $profile_url) {
1674 $recipient = $user_info;
1675 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1676 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
1677 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1678 $sender = $user_info;
1681 if (isset($recipient) && isset($sender)) {
1682 $ret[] = api_format_messages($item, $recipient, $sender);
1686 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
1690 * Returns the most recent direct messages sent by the user.
1692 * @param string $type Return type (atom, rss, xml, json)
1694 * @return array|string
1695 * @throws BadRequestException
1696 * @throws ForbiddenException
1697 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
1699 function api_direct_messages_sentbox($type)
1701 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
1702 return api_direct_messages_box($type, "sentbox", $verbose);
1705 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
1708 * Returns the most recent direct messages sent to the user.
1710 * @param string $type Return type (atom, rss, xml, json)
1712 * @return array|string
1713 * @throws BadRequestException
1714 * @throws ForbiddenException
1715 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
1717 function api_direct_messages_inbox($type)
1719 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
1720 return api_direct_messages_box($type, "inbox", $verbose);
1723 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
1727 * @param string $type Return type (atom, rss, xml, json)
1729 * @return array|string
1730 * @throws BadRequestException
1731 * @throws ForbiddenException
1733 function api_direct_messages_all($type)
1735 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
1736 return api_direct_messages_box($type, "all", $verbose);
1739 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
1743 * @param string $type Return type (atom, rss, xml, json)
1745 * @return array|string
1746 * @throws BadRequestException
1747 * @throws ForbiddenException
1749 function api_direct_messages_conversation($type)
1751 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
1752 return api_direct_messages_box($type, "conversation", $verbose);
1755 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
1758 * list all photos of the authenticated user
1760 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1761 * @return string|array
1762 * @throws ForbiddenException
1763 * @throws InternalServerErrorException
1765 function api_fr_photos_list($type)
1767 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1768 $uid = BaseApi::getCurrentUserID();
1770 $r = DBA::toArray(DBA::p(
1771 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
1772 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
1773 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
1774 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
1777 'image/jpeg' => 'jpg',
1778 'image/png' => 'png',
1779 'image/gif' => 'gif'
1781 $data = ['photo'=>[]];
1782 if (DBA::isResult($r)) {
1783 foreach ($r as $rr) {
1785 $photo['id'] = $rr['resource-id'];
1786 $photo['album'] = $rr['album'];
1787 $photo['filename'] = $rr['filename'];
1788 $photo['type'] = $rr['type'];
1789 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
1790 $photo['created'] = $rr['created'];
1791 $photo['edited'] = $rr['edited'];
1792 $photo['desc'] = $rr['desc'];
1794 if ($type == "xml") {
1795 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
1797 $photo['thumb'] = $thumb;
1798 $data['photo'][] = $photo;
1802 return DI::apiResponse()->formatData("photos", $type, $data);
1805 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
1808 * upload a new photo or change an existing photo
1810 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1811 * @return string|array
1812 * @throws BadRequestException
1813 * @throws ForbiddenException
1814 * @throws ImagickException
1815 * @throws InternalServerErrorException
1816 * @throws NotFoundException
1818 function api_fr_photo_create_update($type)
1820 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1821 $uid = BaseApi::getCurrentUserID();
1824 $photo_id = $_REQUEST['photo_id'] ?? null;
1825 $desc = $_REQUEST['desc'] ?? null;
1826 $album = $_REQUEST['album'] ?? null;
1827 $album_new = $_REQUEST['album_new'] ?? null;
1828 $allow_cid = $_REQUEST['allow_cid'] ?? null;
1829 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
1830 $allow_gid = $_REQUEST['allow_gid'] ?? null;
1831 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
1832 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
1834 // do several checks on input parameters
1835 // we do not allow calls without album string
1836 if ($album == null) {
1837 throw new BadRequestException("no albumname specified");
1839 // if photo_id == null --> we are uploading a new photo
1840 if ($photo_id == null) {
1843 // error if no media posted in create-mode
1844 if (empty($_FILES['media'])) {
1846 throw new BadRequestException("no media data submitted");
1849 // album_new will be ignored in create-mode
1854 // check if photo is existing in databasei
1855 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
1856 throw new BadRequestException("photo not available");
1860 // checks on acl strings provided by clients
1861 $acl_input_error = false;
1862 $acl_input_error |= check_acl_input($allow_cid, $uid);
1863 $acl_input_error |= check_acl_input($deny_cid, $uid);
1864 $acl_input_error |= check_acl_input($allow_gid, $uid);
1865 $acl_input_error |= check_acl_input($deny_gid, $uid);
1866 if ($acl_input_error) {
1867 throw new BadRequestException("acl data invalid");
1869 // now let's upload the new media in create-mode
1870 if ($mode == "create") {
1871 $media = $_FILES['media'];
1872 $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);
1874 // return success of updating or error message
1875 if (!is_null($data)) {
1876 return DI::apiResponse()->formatData("photo_create", $type, $data);
1878 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
1882 // now let's do the changes in update-mode
1883 if ($mode == "update") {
1884 $updated_fields = [];
1886 if (!is_null($desc)) {
1887 $updated_fields['desc'] = $desc;
1890 if (!is_null($album_new)) {
1891 $updated_fields['album'] = $album_new;
1894 if (!is_null($allow_cid)) {
1895 $allow_cid = trim($allow_cid);
1896 $updated_fields['allow_cid'] = $allow_cid;
1899 if (!is_null($deny_cid)) {
1900 $deny_cid = trim($deny_cid);
1901 $updated_fields['deny_cid'] = $deny_cid;
1904 if (!is_null($allow_gid)) {
1905 $allow_gid = trim($allow_gid);
1906 $updated_fields['allow_gid'] = $allow_gid;
1909 if (!is_null($deny_gid)) {
1910 $deny_gid = trim($deny_gid);
1911 $updated_fields['deny_gid'] = $deny_gid;
1915 if (count($updated_fields) > 0) {
1916 $nothingtodo = false;
1917 $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
1919 $nothingtodo = true;
1922 if (!empty($_FILES['media'])) {
1923 $nothingtodo = false;
1924 $media = $_FILES['media'];
1925 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
1926 if (!is_null($data)) {
1927 return DI::apiResponse()->formatData("photo_update", $type, $data);
1931 // return success of updating or error message
1933 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
1934 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1937 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
1938 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1940 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
1943 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
1946 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
1947 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
1950 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
1952 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1953 * @return string|array
1954 * @throws BadRequestException
1955 * @throws ForbiddenException
1956 * @throws InternalServerErrorException
1957 * @throws NotFoundException
1959 function api_fr_photo_detail($type)
1961 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1962 $uid = BaseApi::getCurrentUserID();
1964 if (empty($_REQUEST['photo_id'])) {
1965 throw new BadRequestException("No photo id.");
1968 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
1969 $photo_id = $_REQUEST['photo_id'];
1971 // prepare json/xml output with data from database for the requested photo
1972 $data = prepare_photo_data($type, $scale, $photo_id, $uid);
1974 return DI::apiResponse()->formatData("photo_detail", $type, $data);
1977 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
1980 * updates the profile image for the user (either a specified profile or the default profile)
1982 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1984 * @return string|array
1985 * @throws BadRequestException
1986 * @throws ForbiddenException
1987 * @throws ImagickException
1988 * @throws InternalServerErrorException
1989 * @throws NotFoundException
1990 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
1992 function api_account_update_profile_image($type)
1994 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1995 $uid = BaseApi::getCurrentUserID();
1998 $profile_id = $_REQUEST['profile_id'] ?? 0;
2000 // error if image data is missing
2001 if (empty($_FILES['image'])) {
2002 throw new BadRequestException("no media data submitted");
2005 // check if specified profile id is valid
2006 if ($profile_id != 0) {
2007 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
2008 // error message if specified profile id is not in database
2009 if (!DBA::isResult($profile)) {
2010 throw new BadRequestException("profile_id not available");
2012 $is_default_profile = $profile['is-default'];
2014 $is_default_profile = 1;
2017 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
2019 if (!empty($_FILES['image'])) {
2020 $media = $_FILES['image'];
2021 } elseif (!empty($_FILES['media'])) {
2022 $media = $_FILES['media'];
2024 // save new profile image
2025 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
2028 if (is_array($media['type'])) {
2029 $filetype = $media['type'][0];
2031 $filetype = $media['type'];
2033 if ($filetype == "image/jpeg") {
2035 } elseif ($filetype == "image/png") {
2038 throw new InternalServerErrorException('Unsupported filetype');
2041 // change specified profile or all profiles to the new resource-id
2042 if ($is_default_profile) {
2043 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
2044 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
2046 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
2047 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
2048 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
2051 Contact::updateSelfFromUserID($uid, true);
2053 // Update global directory in background
2054 Profile::publishUpdate($uid);
2056 // output for client
2058 $skip_status = $_REQUEST['skip_status'] ?? false;
2060 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
2062 // "verified" isn't used here in the standard
2063 unset($user_info["verified"]);
2065 // "uid" is only needed for some internal stuff, so remove it from here
2066 unset($user_info['uid']);
2068 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
2070 // SaveMediaToDatabase failed for some reason
2071 throw new InternalServerErrorException("image upload failed");
2075 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
2078 * Return all or a specified group of the user with the containing contacts.
2080 * @param string $type Return type (atom, rss, xml, json)
2082 * @return array|string
2083 * @throws BadRequestException
2084 * @throws ForbiddenException
2085 * @throws ImagickException
2086 * @throws InternalServerErrorException
2087 * @throws UnauthorizedException
2089 function api_friendica_group_show($type)
2091 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2092 $uid = BaseApi::getCurrentUserID();
2095 $gid = $_REQUEST['gid'] ?? 0;
2097 // get data of the specified group id or all groups if not specified
2099 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
2101 // error message if specified gid is not in database
2102 if (!DBA::isResult($groups)) {
2103 throw new BadRequestException("gid not available");
2106 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
2109 // loop through all groups and retrieve all members for adding data in the user array
2111 foreach ($groups as $rr) {
2112 $members = Contact\Group::getById($rr['id']);
2115 if ($type == "xml") {
2116 $user_element = "users";
2118 foreach ($members as $member) {
2119 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
2120 $users[$k++.":user"] = $user;
2123 $user_element = "user";
2124 foreach ($members as $member) {
2125 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
2129 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
2131 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
2134 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
2139 * @param string $type Return type (atom, rss, xml, json)
2141 * @return array|string
2142 * @throws BadRequestException
2143 * @throws ForbiddenException
2144 * @throws ImagickException
2145 * @throws InternalServerErrorException
2146 * @throws UnauthorizedException
2147 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
2149 function api_lists_destroy($type)
2151 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2152 $uid = BaseApi::getCurrentUserID();
2155 $gid = $_REQUEST['list_id'] ?? 0;
2157 // error if no gid specified
2159 throw new BadRequestException('gid not specified');
2162 // get data of the specified group id
2163 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
2164 // error message if specified gid is not in database
2166 throw new BadRequestException('gid not available');
2169 if (Group::remove($gid)) {
2171 'name' => $group['name'],
2172 'id' => intval($gid),
2173 'id_str' => (string) $gid,
2174 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
2177 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
2181 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
2184 * Create the specified group with the posted array of contacts.
2186 * @param string $type Return type (atom, rss, xml, json)
2188 * @return array|string
2189 * @throws BadRequestException
2190 * @throws ForbiddenException
2191 * @throws ImagickException
2192 * @throws InternalServerErrorException
2193 * @throws UnauthorizedException
2195 function api_friendica_group_create($type)
2197 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2198 $uid = BaseApi::getCurrentUserID();
2201 $name = $_REQUEST['name'] ?? '';
2202 $json = json_decode($_POST['json'], true);
2203 $users = $json['user'];
2205 $success = group_create($name, $uid, $users);
2207 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
2210 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
2213 * Create a new group.
2215 * @param string $type Return type (atom, rss, xml, json)
2217 * @return array|string
2218 * @throws BadRequestException
2219 * @throws ForbiddenException
2220 * @throws ImagickException
2221 * @throws InternalServerErrorException
2222 * @throws UnauthorizedException
2223 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
2225 function api_lists_create($type)
2227 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2228 $uid = BaseApi::getCurrentUserID();
2231 $name = $_REQUEST['name'] ?? '';
2233 $success = group_create($name, $uid);
2234 if ($success['success']) {
2236 'name' => $success['name'],
2237 'id' => intval($success['gid']),
2238 'id_str' => (string) $success['gid'],
2239 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
2242 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
2246 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
2249 * Update the specified group with the posted array of contacts.
2251 * @param string $type Return type (atom, rss, xml, json)
2253 * @return array|string
2254 * @throws BadRequestException
2255 * @throws ForbiddenException
2256 * @throws ImagickException
2257 * @throws InternalServerErrorException
2258 * @throws UnauthorizedException
2260 function api_friendica_group_update($type)
2262 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2263 $uid = BaseApi::getCurrentUserID();
2266 $gid = $_REQUEST['gid'] ?? 0;
2267 $name = $_REQUEST['name'] ?? '';
2268 $json = json_decode($_POST['json'], true);
2269 $users = $json['user'];
2271 // error if no name specified
2273 throw new BadRequestException('group name not specified');
2276 // error if no gid specified
2278 throw new BadRequestException('gid not specified');
2282 $members = Contact\Group::getById($gid);
2283 foreach ($members as $member) {
2284 $cid = $member['id'];
2285 foreach ($users as $user) {
2286 $found = ($user['cid'] == $cid ? true : false);
2288 if (!isset($found) || !$found) {
2289 $gid = Group::getIdByName($uid, $name);
2290 Group::removeMember($gid, $cid);
2295 $erroraddinguser = false;
2297 foreach ($users as $user) {
2298 $cid = $user['cid'];
2300 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
2301 Group::addMember($gid, $cid);
2303 $erroraddinguser = true;
2304 $errorusers[] = $cid;
2308 // return success message incl. missing users in array
2309 $status = ($erroraddinguser ? "missing user" : "ok");
2310 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
2311 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
2314 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
2317 * Update information about a group.
2319 * @param string $type Return type (atom, rss, xml, json)
2321 * @return array|string
2322 * @throws BadRequestException
2323 * @throws ForbiddenException
2324 * @throws ImagickException
2325 * @throws InternalServerErrorException
2326 * @throws UnauthorizedException
2327 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
2329 function api_lists_update($type)
2331 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2332 $uid = BaseApi::getCurrentUserID();
2335 $gid = $_REQUEST['list_id'] ?? 0;
2336 $name = $_REQUEST['name'] ?? '';
2338 // error if no gid specified
2340 throw new BadRequestException('gid not specified');
2343 // get data of the specified group id
2344 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
2345 // error message if specified gid is not in database
2347 throw new BadRequestException('gid not available');
2350 if (Group::update($gid, $name)) {
2353 'id' => intval($gid),
2354 'id_str' => (string) $gid,
2355 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
2358 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
2362 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
2365 * search for direct_messages containing a searchstring through api
2367 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2368 * @param string $box
2369 * @return string|array (success: success=true if found and search_result contains found messages,
2370 * success=false if nothing was found, search_result='nothing found',
2371 * error: result=error with error message)
2372 * @throws BadRequestException
2373 * @throws ForbiddenException
2374 * @throws ImagickException
2375 * @throws InternalServerErrorException
2376 * @throws UnauthorizedException
2378 function api_friendica_direct_messages_search($type, $box = "")
2380 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2381 $uid = BaseApi::getCurrentUserID();
2384 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2385 $searchstring = $_REQUEST['searchstring'] ?? '';
2387 // error if no searchstring specified
2388 if ($searchstring == "") {
2389 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
2390 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
2393 // get data for the specified searchstring
2394 $r = DBA::toArray(DBA::p(
2395 "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",
2397 '%'.$searchstring.'%'
2400 $profile_url = $user_info["url"];
2402 // message if nothing was found
2403 if (!DBA::isResult($r)) {
2404 $success = ['success' => false, 'search_results' => 'problem with query'];
2405 } elseif (count($r) == 0) {
2406 $success = ['success' => false, 'search_results' => 'nothing found'];
2409 foreach ($r as $item) {
2410 if ($box == "inbox" || $item['from-url'] != $profile_url) {
2411 $recipient = $user_info;
2412 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2413 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
2414 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2415 $sender = $user_info;
2418 if (isset($recipient) && isset($sender)) {
2419 $ret[] = api_format_messages($item, $recipient, $sender);
2422 $success = ['success' => true, 'search_results' => $ret];
2425 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
2428 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);