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();
414 $arr['uid'] = intval($uid);
416 $arr['type'] = 'photo';
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;
435 'image/jpeg' => 'jpg',
436 'image/png' => 'png',
440 // adds link to the thumbnail scale photo
441 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
442 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
445 // do the magic for storing the item in the database and trigger the federation to other contacts
451 * @param string $type
453 * @param string $photo_id
456 * @throws BadRequestException
457 * @throws ForbiddenException
458 * @throws ImagickException
459 * @throws InternalServerErrorException
460 * @throws NotFoundException
461 * @throws UnauthorizedException
463 function prepare_photo_data($type, $scale, $photo_id, $uid)
465 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
466 $data_sql = ($scale === false ? "" : "data, ");
468 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
469 // clients needs to convert this in their way for further processing
470 $r = DBA::toArray(DBA::p(
471 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
472 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
473 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
474 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
475 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
476 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
482 'image/jpeg' => 'jpg',
483 'image/png' => 'png',
487 // prepare output data for photo
488 if (DBA::isResult($r)) {
489 $data = ['photo' => $r[0]];
490 $data['photo']['id'] = $data['photo']['resource-id'];
491 if ($scale !== false) {
492 $data['photo']['data'] = base64_encode($data['photo']['data']);
494 unset($data['photo']['datasize']); //needed only with scale param
496 if ($type == "xml") {
497 $data['photo']['links'] = [];
498 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
499 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
501 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
504 $data['photo']['link'] = [];
505 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
507 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
508 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
512 unset($data['photo']['resource-id']);
513 unset($data['photo']['minscale']);
514 unset($data['photo']['maxscale']);
516 throw new NotFoundException();
519 // retrieve item element for getting activities (like, dislike etc.) related to photo
520 $condition = ['uid' => $uid, 'resource-id' => $photo_id];
521 $item = Post::selectFirst(['id', 'uid', 'uri', 'uri-id', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
522 if (!DBA::isResult($item)) {
523 throw new NotFoundException('Photo-related item not found.');
526 $data['photo']['friendica_activities'] = DI::friendicaActivities()->createFromUriId($item['uri-id'], $item['uid'], $type);
528 // retrieve comments on photo
529 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
530 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
532 $statuses = Post::selectForUser($uid, [], $condition);
534 // prepare output of comments
536 while ($status = DBA::fetch($statuses)) {
537 $commentData[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'])->toArray();
539 DBA::close($statuses);
542 if ($type == "xml") {
544 foreach ($commentData as $comment) {
545 $comments[$k++ . ":comment"] = $comment;
548 foreach ($commentData as $comment) {
549 $comments[] = $comment;
552 $data['photo']['friendica_comments'] = $comments;
554 // include info if rights on photo and rights on item are mismatching
555 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
556 $data['photo']['deny_cid'] != $item['deny_cid'] ||
557 $data['photo']['allow_gid'] != $item['allow_gid'] ||
558 $data['photo']['deny_gid'] != $item['deny_gid'];
559 $data['photo']['rights_mismatch'] = $rights_mismatch;
566 * @param string $text
569 * @throws InternalServerErrorException
571 function api_clean_plain_items($text)
573 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
575 $text = BBCode::cleanPictureLinks($text);
576 $URLSearchString = "^\[\]";
578 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
580 if ($include_entities == "true") {
581 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
584 // Simplify "attachment" element
585 $text = BBCode::removeAttachment($text);
591 * Add a new group to the database.
593 * @param string $name Group name
594 * @param int $uid User ID
595 * @param array $users List of users to add to the group
598 * @throws BadRequestException
600 function group_create($name, $uid, $users = [])
602 // error if no name specified
604 throw new BadRequestException('group name not specified');
607 // error message if specified group name already exists
608 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
609 throw new BadRequestException('group name already exists');
612 // Check if the group needs to be reactivated
613 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
614 $reactivate_group = true;
618 $ret = Group::create($uid, $name);
620 $gid = Group::getIdByName($uid, $name);
622 throw new BadRequestException('other API error');
626 $erroraddinguser = false;
628 foreach ($users as $user) {
630 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
631 Group::addMember($gid, $cid);
633 $erroraddinguser = true;
634 $errorusers[] = $cid;
638 // return success message incl. missing users in array
639 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
641 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
649 * Returns all lists the user subscribes to.
651 * @param string $type Return type (atom, rss, xml, json)
653 * @return array|string
654 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
656 function api_lists_list($type)
658 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
660 /// @TODO $ret is not filled here?
661 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
664 api_register_func('api/lists/list', 'api_lists_list', true);
665 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
668 * Returns all groups the user owns.
670 * @param string $type Return type (atom, rss, xml, json)
672 * @return array|string
673 * @throws BadRequestException
674 * @throws ForbiddenException
675 * @throws ImagickException
676 * @throws InternalServerErrorException
677 * @throws UnauthorizedException
678 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
680 function api_lists_ownerships($type)
682 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
683 $uid = BaseApi::getCurrentUserID();
686 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
688 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
690 // loop through all groups
692 foreach ($groups as $group) {
693 if ($group['visible']) {
699 'name' => $group['name'],
700 'id' => intval($group['id']),
701 'id_str' => (string) $group['id'],
702 'user' => $user_info,
706 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
709 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
712 * Sends a new direct message.
714 * @param string $type Return type (atom, rss, xml, json)
716 * @return array|string
717 * @throws BadRequestException
718 * @throws ForbiddenException
719 * @throws ImagickException
720 * @throws InternalServerErrorException
721 * @throws NotFoundException
722 * @throws UnauthorizedException
723 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
725 function api_direct_messages_new($type)
727 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
728 $uid = BaseApi::getCurrentUserID();
730 if (empty($_POST["text"]) || empty($_REQUEST['screen_name']) && empty($_REQUEST['user_id'])) {
734 $sender = DI::twitterUser()->createFromUserId($uid, true)->toArray();
736 $cid = BaseApi::getContactIDForSearchterm($_REQUEST['screen_name'] ?? '', $_REQUEST['profileurl'] ?? '', $_REQUEST['user_id'] ?? 0, 0);
738 throw new NotFoundException('Recipient not found');
742 if (!empty($_REQUEST['replyto'])) {
743 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
744 $replyto = $mail['parent-uri'];
745 $sub = $mail['title'];
747 if (!empty($_REQUEST['title'])) {
748 $sub = $_REQUEST['title'];
750 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
754 $cdata = Contact::getPublicAndUserContactID($cid, $uid);
756 $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
759 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
760 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid, true)->toArray(), $sender);
762 $ret = ["error" => $id];
765 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
768 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true);
771 * delete a direct_message from mail table through api
773 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
774 * @return string|array
775 * @throws BadRequestException
776 * @throws ForbiddenException
777 * @throws ImagickException
778 * @throws InternalServerErrorException
779 * @throws UnauthorizedException
780 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
782 function api_direct_messages_destroy($type)
784 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
785 $uid = BaseApi::getCurrentUserID();
788 $id = $_REQUEST['id'] ?? 0;
790 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
791 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
792 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
794 // error if no id or parenturi specified (for clients posting parent-uri as well)
795 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
796 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
797 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
800 // BadRequestException if no id specified (for clients using Twitter API)
802 throw new BadRequestException('Message id not specified');
805 // add parent-uri to sql command if specified by calling app
806 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
808 // error message if specified id is not in database
809 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
810 if ($verbose == "true") {
811 $answer = ['result' => 'error', 'message' => 'message id not in database'];
812 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
814 /// @todo BadRequestException ok for Twitter API clients?
815 throw new BadRequestException('message id not in database');
819 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
821 if ($verbose == "true") {
824 $answer = ['result' => 'ok', 'message' => 'message deleted'];
825 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
827 $answer = ['result' => 'error', 'message' => 'unknown error'];
828 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
831 /// @todo return JSON data like Twitter API not yet implemented
834 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true);
838 * @param string $type Return type (atom, rss, xml, json)
840 * @param string $verbose
842 * @return array|string
843 * @throws BadRequestException
844 * @throws ForbiddenException
845 * @throws ImagickException
846 * @throws InternalServerErrorException
847 * @throws UnauthorizedException
849 function api_direct_messages_box($type, $box, $verbose)
851 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
852 $uid = BaseApi::getCurrentUserID();
855 $count = $_GET['count'] ?? 20;
856 $page = $_REQUEST['page'] ?? 1;
858 $since_id = $_REQUEST['since_id'] ?? 0;
859 $max_id = $_REQUEST['max_id'] ?? 0;
861 $user_id = $_REQUEST['user_id'] ?? '';
862 $screen_name = $_REQUEST['screen_name'] ?? '';
864 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
866 $profile_url = $user_info["url"];
869 $start = max(0, ($page - 1) * $count);
874 if ($box=="sentbox") {
875 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
876 } elseif ($box == "conversation") {
877 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
878 } elseif ($box == "all") {
880 } elseif ($box == "inbox") {
881 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
885 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
888 if ($user_id != "") {
889 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
890 } elseif ($screen_name !="") {
891 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
894 $r = DBA::toArray(DBA::p(
895 "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 ?,?",
901 if ($verbose == "true" && !DBA::isResult($r)) {
902 $answer = ['result' => 'error', 'message' => 'no mails available'];
903 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
907 foreach ($r as $item) {
908 if ($box == "inbox" || $item['from-url'] != $profile_url) {
909 $recipient = $user_info;
910 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
911 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
912 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
913 $sender = $user_info;
916 if (isset($recipient) && isset($sender)) {
917 $ret[] = api_format_messages($item, $recipient, $sender);
921 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
925 * Returns the most recent direct messages sent by the user.
927 * @param string $type Return type (atom, rss, xml, json)
929 * @return array|string
930 * @throws BadRequestException
931 * @throws ForbiddenException
932 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
934 function api_direct_messages_sentbox($type)
936 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
937 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
938 return api_direct_messages_box($type, "sentbox", $verbose);
941 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
944 * Returns the most recent direct messages sent to the user.
946 * @param string $type Return type (atom, rss, xml, json)
948 * @return array|string
949 * @throws BadRequestException
950 * @throws ForbiddenException
951 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
953 function api_direct_messages_inbox($type)
955 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
956 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
957 return api_direct_messages_box($type, "inbox", $verbose);
960 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
964 * @param string $type Return type (atom, rss, xml, json)
966 * @return array|string
967 * @throws BadRequestException
968 * @throws ForbiddenException
970 function api_direct_messages_all($type)
972 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
973 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
974 return api_direct_messages_box($type, "all", $verbose);
977 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
981 * @param string $type Return type (atom, rss, xml, json)
983 * @return array|string
984 * @throws BadRequestException
985 * @throws ForbiddenException
987 function api_direct_messages_conversation($type)
989 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
990 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
991 return api_direct_messages_box($type, "conversation", $verbose);
994 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
997 * list all photos of the authenticated user
999 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1000 * @return string|array
1001 * @throws ForbiddenException
1002 * @throws InternalServerErrorException
1004 function api_fr_photos_list($type)
1006 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1007 $uid = BaseApi::getCurrentUserID();
1009 $r = DBA::toArray(DBA::p(
1010 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
1011 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
1012 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
1013 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
1016 'image/jpeg' => 'jpg',
1017 'image/png' => 'png',
1018 'image/gif' => 'gif'
1020 $data = ['photo'=>[]];
1021 if (DBA::isResult($r)) {
1022 foreach ($r as $rr) {
1024 $photo['id'] = $rr['resource-id'];
1025 $photo['album'] = $rr['album'];
1026 $photo['filename'] = $rr['filename'];
1027 $photo['type'] = $rr['type'];
1028 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
1029 $photo['created'] = $rr['created'];
1030 $photo['edited'] = $rr['edited'];
1031 $photo['desc'] = $rr['desc'];
1033 if ($type == "xml") {
1034 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
1036 $photo['thumb'] = $thumb;
1037 $data['photo'][] = $photo;
1041 return DI::apiResponse()->formatData("photos", $type, $data);
1044 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
1047 * upload a new photo or change an existing photo
1049 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1050 * @return string|array
1051 * @throws BadRequestException
1052 * @throws ForbiddenException
1053 * @throws ImagickException
1054 * @throws InternalServerErrorException
1055 * @throws NotFoundException
1057 function api_fr_photo_create_update($type)
1059 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1060 $uid = BaseApi::getCurrentUserID();
1063 $photo_id = $_REQUEST['photo_id'] ?? null;
1064 $desc = $_REQUEST['desc'] ?? null;
1065 $album = $_REQUEST['album'] ?? null;
1066 $album_new = $_REQUEST['album_new'] ?? null;
1067 $allow_cid = $_REQUEST['allow_cid'] ?? null;
1068 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
1069 $allow_gid = $_REQUEST['allow_gid'] ?? null;
1070 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
1071 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
1073 // do several checks on input parameters
1074 // we do not allow calls without album string
1075 if ($album == null) {
1076 throw new BadRequestException("no albumname specified");
1078 // if photo_id == null --> we are uploading a new photo
1079 if ($photo_id == null) {
1082 // error if no media posted in create-mode
1083 if (empty($_FILES['media'])) {
1085 throw new BadRequestException("no media data submitted");
1088 // album_new will be ignored in create-mode
1093 // check if photo is existing in databasei
1094 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
1095 throw new BadRequestException("photo not available");
1099 // checks on acl strings provided by clients
1100 $acl_input_error = false;
1101 $acl_input_error |= check_acl_input($allow_cid, $uid);
1102 $acl_input_error |= check_acl_input($deny_cid, $uid);
1103 $acl_input_error |= check_acl_input($allow_gid, $uid);
1104 $acl_input_error |= check_acl_input($deny_gid, $uid);
1105 if ($acl_input_error) {
1106 throw new BadRequestException("acl data invalid");
1108 // now let's upload the new media in create-mode
1109 if ($mode == "create") {
1110 $media = $_FILES['media'];
1111 $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);
1113 // return success of updating or error message
1114 if (!is_null($data)) {
1115 return DI::apiResponse()->formatData("photo_create", $type, $data);
1117 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
1121 // now let's do the changes in update-mode
1122 if ($mode == "update") {
1123 $updated_fields = [];
1125 if (!is_null($desc)) {
1126 $updated_fields['desc'] = $desc;
1129 if (!is_null($album_new)) {
1130 $updated_fields['album'] = $album_new;
1133 if (!is_null($allow_cid)) {
1134 $allow_cid = trim($allow_cid);
1135 $updated_fields['allow_cid'] = $allow_cid;
1138 if (!is_null($deny_cid)) {
1139 $deny_cid = trim($deny_cid);
1140 $updated_fields['deny_cid'] = $deny_cid;
1143 if (!is_null($allow_gid)) {
1144 $allow_gid = trim($allow_gid);
1145 $updated_fields['allow_gid'] = $allow_gid;
1148 if (!is_null($deny_gid)) {
1149 $deny_gid = trim($deny_gid);
1150 $updated_fields['deny_gid'] = $deny_gid;
1154 if (count($updated_fields) > 0) {
1155 $nothingtodo = false;
1156 $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
1158 $nothingtodo = true;
1161 if (!empty($_FILES['media'])) {
1162 $nothingtodo = false;
1163 $media = $_FILES['media'];
1164 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
1165 if (!is_null($data)) {
1166 return DI::apiResponse()->formatData("photo_update", $type, $data);
1170 // return success of updating or error message
1172 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
1173 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1176 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
1177 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1179 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
1182 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
1185 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true);
1186 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true);
1189 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
1191 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1192 * @return string|array
1193 * @throws BadRequestException
1194 * @throws ForbiddenException
1195 * @throws InternalServerErrorException
1196 * @throws NotFoundException
1198 function api_fr_photo_detail($type)
1200 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1201 $uid = BaseApi::getCurrentUserID();
1203 if (empty($_REQUEST['photo_id'])) {
1204 throw new BadRequestException("No photo id.");
1207 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
1208 $photo_id = $_REQUEST['photo_id'];
1210 // prepare json/xml output with data from database for the requested photo
1211 $data = prepare_photo_data($type, $scale, $photo_id, $uid);
1213 return DI::apiResponse()->formatData("photo_detail", $type, $data);
1216 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
1219 * updates the profile image for the user (either a specified profile or the default profile)
1221 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1223 * @return string|array
1224 * @throws BadRequestException
1225 * @throws ForbiddenException
1226 * @throws ImagickException
1227 * @throws InternalServerErrorException
1228 * @throws NotFoundException
1229 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
1231 function api_account_update_profile_image($type)
1233 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1234 $uid = BaseApi::getCurrentUserID();
1237 $profile_id = $_REQUEST['profile_id'] ?? 0;
1239 // error if image data is missing
1240 if (empty($_FILES['image'])) {
1241 throw new BadRequestException("no media data submitted");
1244 // check if specified profile id is valid
1245 if ($profile_id != 0) {
1246 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
1247 // error message if specified profile id is not in database
1248 if (!DBA::isResult($profile)) {
1249 throw new BadRequestException("profile_id not available");
1251 $is_default_profile = $profile['is-default'];
1253 $is_default_profile = 1;
1256 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
1258 if (!empty($_FILES['image'])) {
1259 $media = $_FILES['image'];
1260 } elseif (!empty($_FILES['media'])) {
1261 $media = $_FILES['media'];
1263 // save new profile image
1264 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
1267 if (is_array($media['type'])) {
1268 $filetype = $media['type'][0];
1270 $filetype = $media['type'];
1272 if ($filetype == "image/jpeg") {
1274 } elseif ($filetype == "image/png") {
1277 throw new InternalServerErrorException('Unsupported filetype');
1280 // change specified profile or all profiles to the new resource-id
1281 if ($is_default_profile) {
1282 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
1283 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
1285 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
1286 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
1287 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
1290 Contact::updateSelfFromUserID($uid, true);
1292 // Update global directory in background
1293 Profile::publishUpdate($uid);
1295 // output for client
1297 $skip_status = $_REQUEST['skip_status'] ?? false;
1299 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
1301 // "verified" isn't used here in the standard
1302 unset($user_info["verified"]);
1304 // "uid" is only needed for some internal stuff, so remove it from here
1305 unset($user_info['uid']);
1307 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
1309 // SaveMediaToDatabase failed for some reason
1310 throw new InternalServerErrorException("image upload failed");
1314 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true);
1317 * Return all or a specified group of the user with the containing contacts.
1319 * @param string $type Return type (atom, rss, xml, json)
1321 * @return array|string
1322 * @throws BadRequestException
1323 * @throws ForbiddenException
1324 * @throws ImagickException
1325 * @throws InternalServerErrorException
1326 * @throws UnauthorizedException
1328 function api_friendica_group_show($type)
1330 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1331 $uid = BaseApi::getCurrentUserID();
1334 $gid = $_REQUEST['gid'] ?? 0;
1336 // get data of the specified group id or all groups if not specified
1338 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
1340 // error message if specified gid is not in database
1341 if (!DBA::isResult($groups)) {
1342 throw new BadRequestException("gid not available");
1345 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
1348 // loop through all groups and retrieve all members for adding data in the user array
1350 foreach ($groups as $rr) {
1351 $members = Contact\Group::getById($rr['id']);
1354 if ($type == "xml") {
1355 $user_element = "users";
1357 foreach ($members as $member) {
1358 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
1359 $users[$k++.":user"] = $user;
1362 $user_element = "user";
1363 foreach ($members as $member) {
1364 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
1368 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
1370 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
1373 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
1378 * @param string $type Return type (atom, rss, xml, json)
1380 * @return array|string
1381 * @throws BadRequestException
1382 * @throws ForbiddenException
1383 * @throws ImagickException
1384 * @throws InternalServerErrorException
1385 * @throws UnauthorizedException
1386 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
1388 function api_lists_destroy($type)
1390 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1391 $uid = BaseApi::getCurrentUserID();
1394 $gid = $_REQUEST['list_id'] ?? 0;
1396 // error if no gid specified
1398 throw new BadRequestException('gid not specified');
1401 // get data of the specified group id
1402 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1403 // error message if specified gid is not in database
1405 throw new BadRequestException('gid not available');
1408 if (Group::remove($gid)) {
1410 'name' => $group['name'],
1411 'id' => intval($gid),
1412 'id_str' => (string) $gid,
1413 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1416 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1420 api_register_func('api/lists/destroy', 'api_lists_destroy', true);
1423 * Create the specified group with the posted array of contacts.
1425 * @param string $type Return type (atom, rss, xml, json)
1427 * @return array|string
1428 * @throws BadRequestException
1429 * @throws ForbiddenException
1430 * @throws ImagickException
1431 * @throws InternalServerErrorException
1432 * @throws UnauthorizedException
1434 function api_friendica_group_create($type)
1436 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1437 $uid = BaseApi::getCurrentUserID();
1440 $name = $_REQUEST['name'] ?? '';
1441 $json = json_decode($_POST['json'], true);
1442 $users = $json['user'];
1444 $success = group_create($name, $uid, $users);
1446 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
1449 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true);
1452 * Create a new group.
1454 * @param string $type Return type (atom, rss, xml, json)
1456 * @return array|string
1457 * @throws BadRequestException
1458 * @throws ForbiddenException
1459 * @throws ImagickException
1460 * @throws InternalServerErrorException
1461 * @throws UnauthorizedException
1462 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
1464 function api_lists_create($type)
1466 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1467 $uid = BaseApi::getCurrentUserID();
1470 $name = $_REQUEST['name'] ?? '';
1472 $success = group_create($name, $uid);
1473 if ($success['success']) {
1475 'name' => $success['name'],
1476 'id' => intval($success['gid']),
1477 'id_str' => (string) $success['gid'],
1478 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1481 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
1485 api_register_func('api/lists/create', 'api_lists_create', true);
1488 * Update information about a group.
1490 * @param string $type Return type (atom, rss, xml, json)
1492 * @return array|string
1493 * @throws BadRequestException
1494 * @throws ForbiddenException
1495 * @throws ImagickException
1496 * @throws InternalServerErrorException
1497 * @throws UnauthorizedException
1498 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
1500 function api_lists_update($type)
1502 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1503 $uid = BaseApi::getCurrentUserID();
1506 $gid = $_REQUEST['list_id'] ?? 0;
1507 $name = $_REQUEST['name'] ?? '';
1509 // error if no gid specified
1511 throw new BadRequestException('gid not specified');
1514 // get data of the specified group id
1515 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1516 // error message if specified gid is not in database
1518 throw new BadRequestException('gid not available');
1521 if (Group::update($gid, $name)) {
1524 'id' => intval($gid),
1525 'id_str' => (string) $gid,
1526 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1529 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1533 api_register_func('api/lists/update', 'api_lists_update', true);
1536 * search for direct_messages containing a searchstring through api
1538 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1539 * @param string $box
1540 * @return string|array (success: success=true if found and search_result contains found messages,
1541 * success=false if nothing was found, search_result='nothing found',
1542 * error: result=error with error message)
1543 * @throws BadRequestException
1544 * @throws ForbiddenException
1545 * @throws ImagickException
1546 * @throws InternalServerErrorException
1547 * @throws UnauthorizedException
1549 function api_friendica_direct_messages_search($type, $box = "")
1551 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1552 $uid = BaseApi::getCurrentUserID();
1555 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1556 $searchstring = $_REQUEST['searchstring'] ?? '';
1558 // error if no searchstring specified
1559 if ($searchstring == "") {
1560 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
1561 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
1564 // get data for the specified searchstring
1565 $r = DBA::toArray(DBA::p(
1566 "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",
1568 '%'.$searchstring.'%'
1571 $profile_url = $user_info["url"];
1573 // message if nothing was found
1574 if (!DBA::isResult($r)) {
1575 $success = ['success' => false, 'search_results' => 'problem with query'];
1576 } elseif (count($r) == 0) {
1577 $success = ['success' => false, 'search_results' => 'nothing found'];
1580 foreach ($r as $item) {
1581 if ($box == "inbox" || $item['from-url'] != $profile_url) {
1582 $recipient = $user_info;
1583 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1584 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
1585 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1586 $sender = $user_info;
1589 if (isset($recipient) && isset($sender)) {
1590 $ret[] = api_format_messages($item, $recipient, $sender);
1593 $success = ['success' => true, 'search_results' => $ret];
1596 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
1599 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);