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\Photo;
39 use Friendica\Model\Post;
40 use Friendica\Model\Profile;
41 use Friendica\Module\BaseApi;
42 use Friendica\Network\HTTPException;
43 use Friendica\Network\HTTPException\BadRequestException;
44 use Friendica\Network\HTTPException\ForbiddenException;
45 use Friendica\Network\HTTPException\InternalServerErrorException;
46 use Friendica\Network\HTTPException\NotFoundException;
47 use Friendica\Network\HTTPException\UnauthorizedException;
48 use Friendica\Object\Image;
49 use Friendica\Util\DateTimeFormat;
50 use Friendica\Util\Images;
51 use Friendica\Util\Strings;
53 require_once __DIR__ . '/../mod/item.php';
58 * Register a function to be the endpoint for defined API path.
60 * @param string $path API URL path, relative to DI::baseUrl()
61 * @param string $func Function name to call on path request
63 function api_register_func($path, $func)
71 // Workaround for hotot
72 $path = str_replace("api/", "api/1.1/", $path);
80 * Main API entry point
82 * Authenticate user, call registered API function, set HTTP headers
84 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
85 * @return string|array API call result
88 function api_call($command, $extension)
92 Logger::info('Legacy API call', ['command' => $command, 'extension' => $extension]);
95 foreach ($API as $p => $info) {
96 if (strpos($command, $p) === 0) {
97 Logger::debug(BaseApi::LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
99 $stamp = microtime(true);
100 $return = call_user_func($info['func'], $extension);
101 $duration = floatval(microtime(true) - $stamp);
103 Logger::info(BaseApi::LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
105 DI::profiler()->saveLog(DI::logger(), BaseApi::LOG_PREFIX . 'performance');
107 if (false === $return) {
109 * api function returned false withour throw an
110 * exception. This should not happend, throw a 500
112 throw new InternalServerErrorException();
115 switch ($extension) {
117 header("Content-Type: text/xml");
120 header("Content-Type: application/json");
121 if (!empty($return)) {
122 $json = json_encode(end($return));
123 if (!empty($_GET['callback'])) {
124 $json = $_GET['callback'] . "(" . $json . ")";
130 header("Content-Type: application/rss+xml");
131 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
134 header("Content-Type: application/atom+xml");
135 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
142 Logger::warning(BaseApi::LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
143 throw new NotFoundException();
144 } catch (HTTPException $e) {
145 Logger::notice(BaseApi::LOG_PREFIX . 'got exception', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString(), 'error' => $e]);
146 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $extension);
153 * @param array $recipient
154 * @param array $sender
157 * @throws InternalServerErrorException
159 function api_format_messages($item, $recipient, $sender)
161 // standard meta information
164 'sender_id' => $sender['id'],
166 'recipient_id' => $recipient['id'],
167 'created_at' => DateTimeFormat::utc($item['created'] ?? 'now', DateTimeFormat::API),
168 'sender_screen_name' => $sender['screen_name'],
169 'recipient_screen_name' => $recipient['screen_name'],
171 'recipient' => $recipient,
173 'friendica_seen' => $item['seen'] ?? 0,
174 'friendica_parent_uri' => $item['parent-uri'] ?? '',
177 // "uid" is only needed for some internal stuff, so remove it from here
178 if (isset($ret['sender']['uid'])) {
179 unset($ret['sender']['uid']);
181 if (isset($ret['recipient']['uid'])) {
182 unset($ret['recipient']['uid']);
185 //don't send title to regular StatusNET requests to avoid confusing these apps
186 if (!empty($_GET['getText'])) {
187 $ret['title'] = $item['title'];
188 if ($_GET['getText'] == 'html') {
189 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
190 } elseif ($_GET['getText'] == 'plain') {
191 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
194 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
196 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
197 unset($ret['sender']);
198 unset($ret['recipient']);
206 * @param string $acl_string
211 function check_acl_input($acl_string, $uid)
213 if (empty($acl_string)) {
217 $contact_not_found = false;
219 // split <x><y><z> into array of cid's
220 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
222 // check for each cid if it is available on server
223 $cid_array = $array[0];
224 foreach ($cid_array as $cid) {
225 $cid = str_replace("<", "", $cid);
226 $cid = str_replace(">", "", $cid);
227 $condition = ['id' => $cid, 'uid' => $uid];
228 $contact_not_found |= !DBA::exists('contact', $condition);
230 return $contact_not_found;
234 * @param string $mediatype
235 * @param array $media
236 * @param string $type
237 * @param string $album
238 * @param string $allow_cid
239 * @param string $deny_cid
240 * @param string $allow_gid
241 * @param string $deny_gid
242 * @param string $desc
243 * @param integer $phototype
244 * @param boolean $visibility
245 * @param string $photo_id
248 * @throws BadRequestException
249 * @throws ForbiddenException
250 * @throws ImagickException
251 * @throws InternalServerErrorException
252 * @throws NotFoundException
253 * @throws UnauthorizedException
255 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype, $visibility, $photo_id, $uid)
263 if (is_array($media)) {
264 if (is_array($media['tmp_name'])) {
265 $src = $media['tmp_name'][0];
267 $src = $media['tmp_name'];
269 if (is_array($media['name'])) {
270 $filename = basename($media['name'][0]);
272 $filename = basename($media['name']);
274 if (is_array($media['size'])) {
275 $filesize = intval($media['size'][0]);
277 $filesize = intval($media['size']);
279 if (is_array($media['type'])) {
280 $filetype = $media['type'][0];
282 $filetype = $media['type'];
286 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
289 "File upload src: " . $src . " - filename: " . $filename .
290 " - size: " . $filesize . " - type: " . $filetype);
292 // check if there was a php upload error
293 if ($filesize == 0 && $media['error'] == 1) {
294 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
296 // check against max upload size within Friendica instance
297 $maximagesize = DI::config()->get('system', 'maximagesize');
298 if ($maximagesize && ($filesize > $maximagesize)) {
299 $formattedBytes = Strings::formatBytes($maximagesize);
300 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
303 // create Photo instance with the data of the image
304 $imagedata = @file_get_contents($src);
305 $Image = new Image($imagedata, $filetype);
306 if (!$Image->isValid()) {
307 throw new InternalServerErrorException("unable to process image data");
310 // check orientation of image
311 $Image->orient($src);
314 // check max length of images on server
315 $max_length = DI::config()->get('system', 'max_image_length');
316 if ($max_length > 0) {
317 $Image->scaleDown($max_length);
318 logger::info("File upload: Scaling picture to new size " . $max_length);
320 $width = $Image->getWidth();
321 $height = $Image->getHeight();
323 // create a new resource-id if not already provided
324 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
326 if ($mediatype == "photo") {
327 // upload normal image (scales 0, 1, 2)
328 logger::info("photo upload: starting new photo upload");
330 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
332 logger::notice("photo upload: image upload with scale 0 (original size) failed");
334 if ($width > 640 || $height > 640) {
335 $Image->scaleDown(640);
336 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
338 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
342 if ($width > 320 || $height > 320) {
343 $Image->scaleDown(320);
344 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
346 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
349 logger::info("photo upload: new photo upload ended");
350 } elseif ($mediatype == "profileimage") {
351 // upload profile image (scales 4, 5, 6)
352 logger::info("photo upload: starting new profile image upload");
354 if ($width > 300 || $height > 300) {
355 $Image->scaleDown(300);
356 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
358 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
362 if ($width > 80 || $height > 80) {
363 $Image->scaleDown(80);
364 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
366 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
370 if ($width > 48 || $height > 48) {
371 $Image->scaleDown(48);
372 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
374 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
377 $Image->__destruct();
378 logger::info("photo upload: new profile image upload ended");
382 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
383 if ($photo_id == null && $mediatype == "photo") {
384 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid);
386 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
387 return prepare_photo_data($type, false, $resource_id, $uid);
389 throw new InternalServerErrorException("image upload failed");
390 DI::page()->exit(DI::apiResponse());
396 * @param string $hash
397 * @param string $allow_cid
398 * @param string $deny_cid
399 * @param string $allow_gid
400 * @param string $deny_gid
401 * @param string $filetype
402 * @param boolean $visibility
404 * @throws InternalServerErrorException
406 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid)
408 // get data about the api authenticated user
409 $uri = Item::newURI(intval($uid));
410 $owner_record = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
413 $arr['guid'] = System::createUUID();
416 $arr['post-type'] = Item::PT_IMAGE;
418 $arr['resource-id'] = $hash;
419 $arr['contact-id'] = $owner_record['id'];
420 $arr['owner-name'] = $owner_record['name'];
421 $arr['owner-link'] = $owner_record['url'];
422 $arr['owner-avatar'] = $owner_record['thumb'];
423 $arr['author-name'] = $owner_record['name'];
424 $arr['author-link'] = $owner_record['url'];
425 $arr['author-avatar'] = $owner_record['thumb'];
427 $arr['allow_cid'] = $allow_cid;
428 $arr['allow_gid'] = $allow_gid;
429 $arr['deny_cid'] = $deny_cid;
430 $arr['deny_gid'] = $deny_gid;
431 $arr['visible'] = $visibility;
434 $typetoext = Images::supportedTypes();
436 // adds link to the thumbnail scale photo
437 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
438 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
441 // do the magic for storing the item in the database and trigger the federation to other contacts
447 * @param string $type
449 * @param string $photo_id
452 * @throws BadRequestException
453 * @throws ForbiddenException
454 * @throws ImagickException
455 * @throws InternalServerErrorException
456 * @throws NotFoundException
457 * @throws UnauthorizedException
459 function prepare_photo_data($type, $scale, $photo_id, $uid)
461 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
462 $data_sql = ($scale === false ? "" : "data, ");
464 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
465 // clients needs to convert this in their way for further processing
466 $r = DBA::toArray(DBA::p(
467 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
468 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
469 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
470 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
471 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
472 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
478 'image/jpeg' => 'jpg',
479 'image/png' => 'png',
483 // prepare output data for photo
484 if (DBA::isResult($r)) {
485 $data = ['photo' => $r[0]];
486 $data['photo']['id'] = $data['photo']['resource-id'];
487 if ($scale !== false) {
488 $data['photo']['data'] = base64_encode($data['photo']['data']);
490 unset($data['photo']['datasize']); //needed only with scale param
492 if ($type == "xml") {
493 $data['photo']['links'] = [];
494 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
495 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
497 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
500 $data['photo']['link'] = [];
501 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
503 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
504 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
508 unset($data['photo']['resource-id']);
509 unset($data['photo']['minscale']);
510 unset($data['photo']['maxscale']);
512 throw new NotFoundException();
515 // retrieve item element for getting activities (like, dislike etc.) related to photo
516 $condition = ['uid' => $uid, 'resource-id' => $photo_id];
517 $item = Post::selectFirst(['id', 'uid', 'uri', 'uri-id', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
518 if (!DBA::isResult($item)) {
519 throw new NotFoundException('Photo-related item not found.');
522 $data['photo']['friendica_activities'] = DI::friendicaActivities()->createFromUriId($item['uri-id'], $item['uid'], $type);
524 // retrieve comments on photo
525 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
526 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
528 $statuses = Post::selectForUser($uid, [], $condition);
530 // prepare output of comments
532 while ($status = DBA::fetch($statuses)) {
533 $commentData[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'])->toArray();
535 DBA::close($statuses);
538 if ($type == "xml") {
540 foreach ($commentData as $comment) {
541 $comments[$k++ . ":comment"] = $comment;
544 foreach ($commentData as $comment) {
545 $comments[] = $comment;
548 $data['photo']['friendica_comments'] = $comments;
550 // include info if rights on photo and rights on item are mismatching
551 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
552 $data['photo']['deny_cid'] != $item['deny_cid'] ||
553 $data['photo']['allow_gid'] != $item['allow_gid'] ||
554 $data['photo']['deny_gid'] != $item['deny_gid'];
555 $data['photo']['rights_mismatch'] = $rights_mismatch;
562 * @param string $text
565 * @throws InternalServerErrorException
567 function api_clean_plain_items($text)
569 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
571 $text = BBCode::cleanPictureLinks($text);
572 $URLSearchString = "^\[\]";
574 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
576 if ($include_entities == "true") {
577 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
580 // Simplify "attachment" element
581 $text = BBCode::removeAttachment($text);
587 * Add a new group to the database.
589 * @param string $name Group name
590 * @param int $uid User ID
591 * @param array $users List of users to add to the group
594 * @throws BadRequestException
596 function group_create($name, $uid, $users = [])
598 // error if no name specified
600 throw new BadRequestException('group name not specified');
603 // error message if specified group name already exists
604 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
605 throw new BadRequestException('group name already exists');
608 // Check if the group needs to be reactivated
609 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
610 $reactivate_group = true;
614 $ret = Group::create($uid, $name);
616 $gid = Group::getIdByName($uid, $name);
618 throw new BadRequestException('other API error');
622 $erroraddinguser = false;
624 foreach ($users as $user) {
626 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
627 Group::addMember($gid, $cid);
629 $erroraddinguser = true;
630 $errorusers[] = $cid;
634 // return success message incl. missing users in array
635 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
637 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
645 * Returns all lists the user subscribes to.
647 * @param string $type Return type (atom, rss, xml, json)
649 * @return array|string
650 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
652 function api_lists_list($type)
654 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
656 /// @TODO $ret is not filled here?
657 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
660 api_register_func('api/lists/list', 'api_lists_list', true);
661 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
664 * Returns all groups the user owns.
666 * @param string $type Return type (atom, rss, xml, json)
668 * @return array|string
669 * @throws BadRequestException
670 * @throws ForbiddenException
671 * @throws ImagickException
672 * @throws InternalServerErrorException
673 * @throws UnauthorizedException
674 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
676 function api_lists_ownerships($type)
678 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
679 $uid = BaseApi::getCurrentUserID();
682 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
684 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
686 // loop through all groups
688 foreach ($groups as $group) {
689 if ($group['visible']) {
695 'name' => $group['name'],
696 'id' => intval($group['id']),
697 'id_str' => (string) $group['id'],
698 'user' => $user_info,
702 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
705 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
708 * Sends a new direct message.
710 * @param string $type Return type (atom, rss, xml, json)
712 * @return array|string
713 * @throws BadRequestException
714 * @throws ForbiddenException
715 * @throws ImagickException
716 * @throws InternalServerErrorException
717 * @throws NotFoundException
718 * @throws UnauthorizedException
719 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
721 function api_direct_messages_new($type)
723 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
724 $uid = BaseApi::getCurrentUserID();
726 if (empty($_POST["text"]) || empty($_REQUEST['screen_name']) && empty($_REQUEST['user_id'])) {
730 $sender = DI::twitterUser()->createFromUserId($uid, true)->toArray();
732 $cid = BaseApi::getContactIDForSearchterm($_REQUEST['screen_name'] ?? '', $_REQUEST['profileurl'] ?? '', $_REQUEST['user_id'] ?? 0, 0);
734 throw new NotFoundException('Recipient not found');
738 if (!empty($_REQUEST['replyto'])) {
739 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
740 $replyto = $mail['parent-uri'];
741 $sub = $mail['title'];
743 if (!empty($_REQUEST['title'])) {
744 $sub = $_REQUEST['title'];
746 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
750 $cdata = Contact::getPublicAndUserContactID($cid, $uid);
752 $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
755 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
756 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid, true)->toArray(), $sender);
758 $ret = ["error" => $id];
761 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
764 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true);
767 * delete a direct_message from mail table through api
769 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
770 * @return string|array
771 * @throws BadRequestException
772 * @throws ForbiddenException
773 * @throws ImagickException
774 * @throws InternalServerErrorException
775 * @throws UnauthorizedException
776 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
778 function api_direct_messages_destroy($type)
780 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
781 $uid = BaseApi::getCurrentUserID();
784 $id = $_REQUEST['id'] ?? 0;
786 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
787 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
788 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
790 // error if no id or parenturi specified (for clients posting parent-uri as well)
791 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
792 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
793 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
796 // BadRequestException if no id specified (for clients using Twitter API)
798 throw new BadRequestException('Message id not specified');
801 // add parent-uri to sql command if specified by calling app
802 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
804 // error message if specified id is not in database
805 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
806 if ($verbose == "true") {
807 $answer = ['result' => 'error', 'message' => 'message id not in database'];
808 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
810 /// @todo BadRequestException ok for Twitter API clients?
811 throw new BadRequestException('message id not in database');
815 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
817 if ($verbose == "true") {
820 $answer = ['result' => 'ok', 'message' => 'message deleted'];
821 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
823 $answer = ['result' => 'error', 'message' => 'unknown error'];
824 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
827 /// @todo return JSON data like Twitter API not yet implemented
830 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true);
834 * @param string $type Return type (atom, rss, xml, json)
836 * @param string $verbose
838 * @return array|string
839 * @throws BadRequestException
840 * @throws ForbiddenException
841 * @throws ImagickException
842 * @throws InternalServerErrorException
843 * @throws UnauthorizedException
845 function api_direct_messages_box($type, $box, $verbose)
847 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
848 $uid = BaseApi::getCurrentUserID();
851 $count = $_GET['count'] ?? 20;
852 $page = $_REQUEST['page'] ?? 1;
854 $since_id = $_REQUEST['since_id'] ?? 0;
855 $max_id = $_REQUEST['max_id'] ?? 0;
857 $user_id = $_REQUEST['user_id'] ?? '';
858 $screen_name = $_REQUEST['screen_name'] ?? '';
860 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
862 $profile_url = $user_info["url"];
865 $start = max(0, ($page - 1) * $count);
870 if ($box=="sentbox") {
871 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
872 } elseif ($box == "conversation") {
873 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
874 } elseif ($box == "all") {
876 } elseif ($box == "inbox") {
877 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
881 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
884 if ($user_id != "") {
885 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
886 } elseif ($screen_name !="") {
887 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
890 $r = DBA::toArray(DBA::p(
891 "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 ?,?",
897 if ($verbose == "true" && !DBA::isResult($r)) {
898 $answer = ['result' => 'error', 'message' => 'no mails available'];
899 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
903 foreach ($r as $item) {
904 if ($box == "inbox" || $item['from-url'] != $profile_url) {
905 $recipient = $user_info;
906 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
907 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
908 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
909 $sender = $user_info;
912 if (isset($recipient) && isset($sender)) {
913 $ret[] = api_format_messages($item, $recipient, $sender);
917 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
921 * Returns the most recent direct messages sent by the user.
923 * @param string $type Return type (atom, rss, xml, json)
925 * @return array|string
926 * @throws BadRequestException
927 * @throws ForbiddenException
928 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
930 function api_direct_messages_sentbox($type)
932 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
933 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
934 return api_direct_messages_box($type, "sentbox", $verbose);
937 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
940 * Returns the most recent direct messages sent to the user.
942 * @param string $type Return type (atom, rss, xml, json)
944 * @return array|string
945 * @throws BadRequestException
946 * @throws ForbiddenException
947 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
949 function api_direct_messages_inbox($type)
951 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
952 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
953 return api_direct_messages_box($type, "inbox", $verbose);
956 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
960 * @param string $type Return type (atom, rss, xml, json)
962 * @return array|string
963 * @throws BadRequestException
964 * @throws ForbiddenException
966 function api_direct_messages_all($type)
968 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
969 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
970 return api_direct_messages_box($type, "all", $verbose);
973 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
977 * @param string $type Return type (atom, rss, xml, json)
979 * @return array|string
980 * @throws BadRequestException
981 * @throws ForbiddenException
983 function api_direct_messages_conversation($type)
985 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
986 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
987 return api_direct_messages_box($type, "conversation", $verbose);
990 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
993 * list all photos of the authenticated user
995 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
996 * @return string|array
997 * @throws ForbiddenException
998 * @throws InternalServerErrorException
1000 function api_fr_photos_list($type)
1002 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1003 $uid = BaseApi::getCurrentUserID();
1005 $r = DBA::toArray(DBA::p(
1006 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
1007 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
1008 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
1009 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
1012 'image/jpeg' => 'jpg',
1013 'image/png' => 'png',
1014 'image/gif' => 'gif'
1016 $data = ['photo'=>[]];
1017 if (DBA::isResult($r)) {
1018 foreach ($r as $rr) {
1020 $photo['id'] = $rr['resource-id'];
1021 $photo['album'] = $rr['album'];
1022 $photo['filename'] = $rr['filename'];
1023 $photo['type'] = $rr['type'];
1024 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
1025 $photo['created'] = $rr['created'];
1026 $photo['edited'] = $rr['edited'];
1027 $photo['desc'] = $rr['desc'];
1029 if ($type == "xml") {
1030 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
1032 $photo['thumb'] = $thumb;
1033 $data['photo'][] = $photo;
1037 return DI::apiResponse()->formatData("photos", $type, $data);
1040 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
1043 * upload a new photo or change an existing photo
1045 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1046 * @return string|array
1047 * @throws BadRequestException
1048 * @throws ForbiddenException
1049 * @throws ImagickException
1050 * @throws InternalServerErrorException
1051 * @throws NotFoundException
1053 function api_fr_photo_create_update($type)
1055 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1056 $uid = BaseApi::getCurrentUserID();
1059 $photo_id = $_REQUEST['photo_id'] ?? null;
1060 $desc = $_REQUEST['desc'] ?? null;
1061 $album = $_REQUEST['album'] ?? null;
1062 $album_new = $_REQUEST['album_new'] ?? null;
1063 $allow_cid = $_REQUEST['allow_cid'] ?? null;
1064 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
1065 $allow_gid = $_REQUEST['allow_gid'] ?? null;
1066 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
1067 // Pictures uploaded via API never get posted as a visible status
1068 // See https://github.com/friendica/friendica/issues/10990
1069 $visibility = false;
1071 // do several checks on input parameters
1072 // we do not allow calls without album string
1073 if ($album == null) {
1074 throw new BadRequestException("no albumname specified");
1076 // if photo_id == null --> we are uploading a new photo
1077 if ($photo_id == null) {
1080 // error if no media posted in create-mode
1081 if (empty($_FILES['media'])) {
1083 throw new BadRequestException("no media data submitted");
1086 // album_new will be ignored in create-mode
1091 // check if photo is existing in databasei
1092 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
1093 throw new BadRequestException("photo not available");
1097 // checks on acl strings provided by clients
1098 $acl_input_error = false;
1099 $acl_input_error |= check_acl_input($allow_cid, $uid);
1100 $acl_input_error |= check_acl_input($deny_cid, $uid);
1101 $acl_input_error |= check_acl_input($allow_gid, $uid);
1102 $acl_input_error |= check_acl_input($deny_gid, $uid);
1103 if ($acl_input_error) {
1104 throw new BadRequestException("acl data invalid");
1106 // now let's upload the new media in create-mode
1107 if ($mode == "create") {
1108 $media = $_FILES['media'];
1109 $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);
1111 // return success of updating or error message
1112 if (!is_null($data)) {
1113 return DI::apiResponse()->formatData("photo_create", $type, $data);
1115 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
1119 // now let's do the changes in update-mode
1120 if ($mode == "update") {
1121 $updated_fields = [];
1123 if (!is_null($desc)) {
1124 $updated_fields['desc'] = $desc;
1127 if (!is_null($album_new)) {
1128 $updated_fields['album'] = $album_new;
1131 if (!is_null($allow_cid)) {
1132 $allow_cid = trim($allow_cid);
1133 $updated_fields['allow_cid'] = $allow_cid;
1136 if (!is_null($deny_cid)) {
1137 $deny_cid = trim($deny_cid);
1138 $updated_fields['deny_cid'] = $deny_cid;
1141 if (!is_null($allow_gid)) {
1142 $allow_gid = trim($allow_gid);
1143 $updated_fields['allow_gid'] = $allow_gid;
1146 if (!is_null($deny_gid)) {
1147 $deny_gid = trim($deny_gid);
1148 $updated_fields['deny_gid'] = $deny_gid;
1152 if (count($updated_fields) > 0) {
1153 $nothingtodo = false;
1154 $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
1156 $nothingtodo = true;
1159 if (!empty($_FILES['media'])) {
1160 $nothingtodo = false;
1161 $media = $_FILES['media'];
1162 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
1163 if (!is_null($data)) {
1164 return DI::apiResponse()->formatData("photo_update", $type, $data);
1168 // return success of updating or error message
1170 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
1171 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1174 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
1175 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1177 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
1180 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
1183 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true);
1184 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true);
1187 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
1189 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1190 * @return string|array
1191 * @throws BadRequestException
1192 * @throws ForbiddenException
1193 * @throws InternalServerErrorException
1194 * @throws NotFoundException
1196 function api_fr_photo_detail($type)
1198 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1199 $uid = BaseApi::getCurrentUserID();
1201 if (empty($_REQUEST['photo_id'])) {
1202 throw new BadRequestException("No photo id.");
1205 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
1206 $photo_id = $_REQUEST['photo_id'];
1208 // prepare json/xml output with data from database for the requested photo
1209 $data = prepare_photo_data($type, $scale, $photo_id, $uid);
1211 return DI::apiResponse()->formatData("photo_detail", $type, $data);
1214 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
1217 * updates the profile image for the user (either a specified profile or the default profile)
1219 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1221 * @return string|array
1222 * @throws BadRequestException
1223 * @throws ForbiddenException
1224 * @throws ImagickException
1225 * @throws InternalServerErrorException
1226 * @throws NotFoundException
1227 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
1229 function api_account_update_profile_image($type)
1231 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1232 $uid = BaseApi::getCurrentUserID();
1235 $profile_id = $_REQUEST['profile_id'] ?? 0;
1237 // error if image data is missing
1238 if (empty($_FILES['image'])) {
1239 throw new BadRequestException("no media data submitted");
1242 // check if specified profile id is valid
1243 if ($profile_id != 0) {
1244 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
1245 // error message if specified profile id is not in database
1246 if (!DBA::isResult($profile)) {
1247 throw new BadRequestException("profile_id not available");
1249 $is_default_profile = $profile['is-default'];
1251 $is_default_profile = 1;
1254 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
1256 if (!empty($_FILES['image'])) {
1257 $media = $_FILES['image'];
1258 } elseif (!empty($_FILES['media'])) {
1259 $media = $_FILES['media'];
1261 // save new profile image
1262 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
1265 if (is_array($media['type'])) {
1266 $filetype = $media['type'][0];
1268 $filetype = $media['type'];
1270 if ($filetype == "image/jpeg") {
1272 } elseif ($filetype == "image/png") {
1275 throw new InternalServerErrorException('Unsupported filetype');
1278 // change specified profile or all profiles to the new resource-id
1279 if ($is_default_profile) {
1280 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
1281 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
1283 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
1284 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
1285 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
1288 Contact::updateSelfFromUserID($uid, true);
1290 // Update global directory in background
1291 Profile::publishUpdate($uid);
1293 // output for client
1295 $skip_status = $_REQUEST['skip_status'] ?? false;
1297 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
1299 // "verified" isn't used here in the standard
1300 unset($user_info["verified"]);
1302 // "uid" is only needed for some internal stuff, so remove it from here
1303 unset($user_info['uid']);
1305 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
1307 // SaveMediaToDatabase failed for some reason
1308 throw new InternalServerErrorException("image upload failed");
1312 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true);
1315 * Return all or a specified group of the user with the containing contacts.
1317 * @param string $type Return type (atom, rss, xml, json)
1319 * @return array|string
1320 * @throws BadRequestException
1321 * @throws ForbiddenException
1322 * @throws ImagickException
1323 * @throws InternalServerErrorException
1324 * @throws UnauthorizedException
1326 function api_friendica_group_show($type)
1328 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1329 $uid = BaseApi::getCurrentUserID();
1332 $gid = $_REQUEST['gid'] ?? 0;
1334 // get data of the specified group id or all groups if not specified
1336 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
1338 // error message if specified gid is not in database
1339 if (!DBA::isResult($groups)) {
1340 throw new BadRequestException("gid not available");
1343 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
1346 // loop through all groups and retrieve all members for adding data in the user array
1348 foreach ($groups as $rr) {
1349 $members = Contact\Group::getById($rr['id']);
1352 if ($type == "xml") {
1353 $user_element = "users";
1355 foreach ($members as $member) {
1356 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
1357 $users[$k++.":user"] = $user;
1360 $user_element = "user";
1361 foreach ($members as $member) {
1362 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
1366 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
1368 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
1371 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
1376 * @param string $type Return type (atom, rss, xml, json)
1378 * @return array|string
1379 * @throws BadRequestException
1380 * @throws ForbiddenException
1381 * @throws ImagickException
1382 * @throws InternalServerErrorException
1383 * @throws UnauthorizedException
1384 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
1386 function api_lists_destroy($type)
1388 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1389 $uid = BaseApi::getCurrentUserID();
1392 $gid = $_REQUEST['list_id'] ?? 0;
1394 // error if no gid specified
1396 throw new BadRequestException('gid not specified');
1399 // get data of the specified group id
1400 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1401 // error message if specified gid is not in database
1403 throw new BadRequestException('gid not available');
1406 if (Group::remove($gid)) {
1408 'name' => $group['name'],
1409 'id' => intval($gid),
1410 'id_str' => (string) $gid,
1411 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1414 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1418 api_register_func('api/lists/destroy', 'api_lists_destroy', true);
1421 * Create the specified group with the posted array of contacts.
1423 * @param string $type Return type (atom, rss, xml, json)
1425 * @return array|string
1426 * @throws BadRequestException
1427 * @throws ForbiddenException
1428 * @throws ImagickException
1429 * @throws InternalServerErrorException
1430 * @throws UnauthorizedException
1432 function api_friendica_group_create($type)
1434 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1435 $uid = BaseApi::getCurrentUserID();
1438 $name = $_REQUEST['name'] ?? '';
1439 $json = json_decode($_POST['json'], true);
1440 $users = $json['user'];
1442 $success = group_create($name, $uid, $users);
1444 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
1447 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true);
1450 * Create a new group.
1452 * @param string $type Return type (atom, rss, xml, json)
1454 * @return array|string
1455 * @throws BadRequestException
1456 * @throws ForbiddenException
1457 * @throws ImagickException
1458 * @throws InternalServerErrorException
1459 * @throws UnauthorizedException
1460 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
1462 function api_lists_create($type)
1464 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1465 $uid = BaseApi::getCurrentUserID();
1468 $name = $_REQUEST['name'] ?? '';
1470 $success = group_create($name, $uid);
1471 if ($success['success']) {
1473 'name' => $success['name'],
1474 'id' => intval($success['gid']),
1475 'id_str' => (string) $success['gid'],
1476 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1479 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
1483 api_register_func('api/lists/create', 'api_lists_create', true);
1486 * Update information about a group.
1488 * @param string $type Return type (atom, rss, xml, json)
1490 * @return array|string
1491 * @throws BadRequestException
1492 * @throws ForbiddenException
1493 * @throws ImagickException
1494 * @throws InternalServerErrorException
1495 * @throws UnauthorizedException
1496 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
1498 function api_lists_update($type)
1500 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1501 $uid = BaseApi::getCurrentUserID();
1504 $gid = $_REQUEST['list_id'] ?? 0;
1505 $name = $_REQUEST['name'] ?? '';
1507 // error if no gid specified
1509 throw new BadRequestException('gid not specified');
1512 // get data of the specified group id
1513 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1514 // error message if specified gid is not in database
1516 throw new BadRequestException('gid not available');
1519 if (Group::update($gid, $name)) {
1522 'id' => intval($gid),
1523 'id_str' => (string) $gid,
1524 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1527 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1531 api_register_func('api/lists/update', 'api_lists_update', true);
1534 * search for direct_messages containing a searchstring through api
1536 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1537 * @param string $box
1538 * @return string|array (success: success=true if found and search_result contains found messages,
1539 * success=false if nothing was found, search_result='nothing found',
1540 * error: result=error with error message)
1541 * @throws BadRequestException
1542 * @throws ForbiddenException
1543 * @throws ImagickException
1544 * @throws InternalServerErrorException
1545 * @throws UnauthorizedException
1547 function api_friendica_direct_messages_search($type, $box = "")
1549 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1550 $uid = BaseApi::getCurrentUserID();
1553 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1554 $searchstring = $_REQUEST['searchstring'] ?? '';
1556 // error if no searchstring specified
1557 if ($searchstring == "") {
1558 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
1559 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
1562 // get data for the specified searchstring
1563 $r = DBA::toArray(DBA::p(
1564 "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",
1566 '%'.$searchstring.'%'
1569 $profile_url = $user_info["url"];
1571 // message if nothing was found
1572 if (!DBA::isResult($r)) {
1573 $success = ['success' => false, 'search_results' => 'problem with query'];
1574 } elseif (count($r) == 0) {
1575 $success = ['success' => false, 'search_results' => 'nothing found'];
1578 foreach ($r as $item) {
1579 if ($box == "inbox" || $item['from-url'] != $profile_url) {
1580 $recipient = $user_info;
1581 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1582 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
1583 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1584 $sender = $user_info;
1587 if (isset($recipient) && isset($sender)) {
1588 $ret[] = api_format_messages($item, $recipient, $sender);
1591 $success = ['success' => true, 'search_results' => $ret];
1594 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
1597 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);