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\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Group;
35 use Friendica\Model\Item;
36 use Friendica\Model\Mail;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Post;
39 use Friendica\Model\Profile;
40 use Friendica\Module\BaseApi;
41 use Friendica\Network\HTTPException;
42 use Friendica\Network\HTTPException\BadRequestException;
43 use Friendica\Network\HTTPException\ForbiddenException;
44 use Friendica\Network\HTTPException\InternalServerErrorException;
45 use Friendica\Network\HTTPException\NotFoundException;
46 use Friendica\Network\HTTPException\UnauthorizedException;
47 use Friendica\Object\Image;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Images;
50 use Friendica\Util\Strings;
55 * Register a function to be the endpoint for defined API path.
57 * @param string $path API URL path, relative to DI::baseUrl()
58 * @param string $func Function name to call on path request
60 function api_register_func($path, $func)
68 // Workaround for hotot
69 $path = str_replace("api/", "api/1.1/", $path);
77 * Main API entry point
79 * Authenticate user, call registered API function, set HTTP headers
81 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
82 * @return string|array API call result
85 function api_call($command, $extension)
89 Logger::info('Legacy API call', ['command' => $command, 'extension' => $extension]);
92 foreach ($API as $p => $info) {
93 if (strpos($command, $p) === 0) {
94 Logger::debug(BaseApi::LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
96 $stamp = microtime(true);
97 $return = call_user_func($info['func'], $extension);
98 $duration = floatval(microtime(true) - $stamp);
100 Logger::info(BaseApi::LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
102 DI::profiler()->saveLog(DI::logger(), BaseApi::LOG_PREFIX . 'performance');
104 if (false === $return) {
106 * api function returned false withour throw an
107 * exception. This should not happend, throw a 500
109 throw new InternalServerErrorException();
112 switch ($extension) {
114 header("Content-Type: text/xml");
117 header("Content-Type: application/json");
118 if (!empty($return)) {
119 $json = json_encode(end($return));
120 if (!empty($_GET['callback'])) {
121 $json = $_GET['callback'] . "(" . $json . ")";
127 header("Content-Type: application/rss+xml");
128 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
131 header("Content-Type: application/atom+xml");
132 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
139 Logger::warning(BaseApi::LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
140 throw new NotFoundException();
141 } catch (HTTPException $e) {
142 Logger::notice(BaseApi::LOG_PREFIX . 'got exception', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString(), 'error' => $e]);
143 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $extension);
150 * @param array $recipient
151 * @param array $sender
154 * @throws InternalServerErrorException
156 function api_format_messages($item, $recipient, $sender)
158 // standard meta information
161 'sender_id' => $sender['id'],
163 'recipient_id' => $recipient['id'],
164 'created_at' => DateTimeFormat::utc($item['created'] ?? 'now', DateTimeFormat::API),
165 'sender_screen_name' => $sender['screen_name'],
166 'recipient_screen_name' => $recipient['screen_name'],
168 'recipient' => $recipient,
170 'friendica_seen' => $item['seen'] ?? 0,
171 'friendica_parent_uri' => $item['parent-uri'] ?? '',
174 // "uid" is only needed for some internal stuff, so remove it from here
175 if (isset($ret['sender']['uid'])) {
176 unset($ret['sender']['uid']);
178 if (isset($ret['recipient']['uid'])) {
179 unset($ret['recipient']['uid']);
182 //don't send title to regular StatusNET requests to avoid confusing these apps
183 if (!empty($_GET['getText'])) {
184 $ret['title'] = $item['title'];
185 if ($_GET['getText'] == 'html') {
186 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
187 } elseif ($_GET['getText'] == 'plain') {
188 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
191 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
193 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
194 unset($ret['sender']);
195 unset($ret['recipient']);
203 * @param string $acl_string
208 function check_acl_input($acl_string, $uid)
210 if (empty($acl_string)) {
214 $contact_not_found = false;
216 // split <x><y><z> into array of cid's
217 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
219 // check for each cid if it is available on server
220 $cid_array = $array[0];
221 foreach ($cid_array as $cid) {
222 $cid = str_replace("<", "", $cid);
223 $cid = str_replace(">", "", $cid);
224 $condition = ['id' => $cid, 'uid' => $uid];
225 $contact_not_found |= !DBA::exists('contact', $condition);
227 return $contact_not_found;
231 * @param string $mediatype
232 * @param array $media
233 * @param string $type
234 * @param string $album
235 * @param string $allow_cid
236 * @param string $deny_cid
237 * @param string $allow_gid
238 * @param string $deny_gid
239 * @param string $desc
240 * @param integer $phototype
241 * @param boolean $visibility
242 * @param string $photo_id
245 * @throws BadRequestException
246 * @throws ForbiddenException
247 * @throws ImagickException
248 * @throws InternalServerErrorException
249 * @throws NotFoundException
250 * @throws UnauthorizedException
252 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype, $visibility, $photo_id, $uid)
260 if (is_array($media)) {
261 if (is_array($media['tmp_name'])) {
262 $src = $media['tmp_name'][0];
264 $src = $media['tmp_name'];
266 if (is_array($media['name'])) {
267 $filename = basename($media['name'][0]);
269 $filename = basename($media['name']);
271 if (is_array($media['size'])) {
272 $filesize = intval($media['size'][0]);
274 $filesize = intval($media['size']);
276 if (is_array($media['type'])) {
277 $filetype = $media['type'][0];
279 $filetype = $media['type'];
283 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
286 "File upload src: " . $src . " - filename: " . $filename .
287 " - size: " . $filesize . " - type: " . $filetype);
289 // check if there was a php upload error
290 if ($filesize == 0 && $media['error'] == 1) {
291 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
293 // check against max upload size within Friendica instance
294 $maximagesize = DI::config()->get('system', 'maximagesize');
295 if ($maximagesize && ($filesize > $maximagesize)) {
296 $formattedBytes = Strings::formatBytes($maximagesize);
297 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
300 // create Photo instance with the data of the image
301 $imagedata = @file_get_contents($src);
302 $Image = new Image($imagedata, $filetype);
303 if (!$Image->isValid()) {
304 throw new InternalServerErrorException("unable to process image data");
307 // check orientation of image
308 $Image->orient($src);
311 // check max length of images on server
312 $max_length = DI::config()->get('system', 'max_image_length');
313 if ($max_length > 0) {
314 $Image->scaleDown($max_length);
315 logger::info("File upload: Scaling picture to new size " . $max_length);
317 $width = $Image->getWidth();
318 $height = $Image->getHeight();
320 // create a new resource-id if not already provided
321 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
323 if ($mediatype == "photo") {
324 // upload normal image (scales 0, 1, 2)
325 logger::info("photo upload: starting new photo upload");
327 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
329 logger::notice("photo upload: image upload with scale 0 (original size) failed");
331 if ($width > 640 || $height > 640) {
332 $Image->scaleDown(640);
333 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
335 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
339 if ($width > 320 || $height > 320) {
340 $Image->scaleDown(320);
341 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
343 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
346 logger::info("photo upload: new photo upload ended");
347 } elseif ($mediatype == "profileimage") {
348 // upload profile image (scales 4, 5, 6)
349 logger::info("photo upload: starting new profile image upload");
351 if ($width > 300 || $height > 300) {
352 $Image->scaleDown(300);
353 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
355 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
359 if ($width > 80 || $height > 80) {
360 $Image->scaleDown(80);
361 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
363 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
367 if ($width > 48 || $height > 48) {
368 $Image->scaleDown(48);
369 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
371 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
374 $Image->__destruct();
375 logger::info("photo upload: new profile image upload ended");
379 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
380 if ($photo_id == null && $mediatype == "photo") {
381 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid);
383 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
384 return prepare_photo_data($type, false, $resource_id, $uid);
386 throw new InternalServerErrorException("image upload failed");
387 DI::page()->exit(DI::apiResponse());
393 * @param string $hash
394 * @param string $allow_cid
395 * @param string $deny_cid
396 * @param string $allow_gid
397 * @param string $deny_gid
398 * @param string $filetype
399 * @param boolean $visibility
401 * @throws InternalServerErrorException
403 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid)
405 // get data about the api authenticated user
406 $uri = Item::newURI(intval($uid));
407 $owner_record = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
410 $arr['guid'] = System::createUUID();
413 $arr['post-type'] = Item::PT_IMAGE;
415 $arr['resource-id'] = $hash;
416 $arr['contact-id'] = $owner_record['id'];
417 $arr['owner-name'] = $owner_record['name'];
418 $arr['owner-link'] = $owner_record['url'];
419 $arr['owner-avatar'] = $owner_record['thumb'];
420 $arr['author-name'] = $owner_record['name'];
421 $arr['author-link'] = $owner_record['url'];
422 $arr['author-avatar'] = $owner_record['thumb'];
424 $arr['allow_cid'] = $allow_cid;
425 $arr['allow_gid'] = $allow_gid;
426 $arr['deny_cid'] = $deny_cid;
427 $arr['deny_gid'] = $deny_gid;
428 $arr['visible'] = $visibility;
431 $typetoext = Images::supportedTypes();
433 // adds link to the thumbnail scale photo
434 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
435 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
438 // do the magic for storing the item in the database and trigger the federation to other contacts
444 * @param string $type
446 * @param string $photo_id
449 * @throws BadRequestException
450 * @throws ForbiddenException
451 * @throws ImagickException
452 * @throws InternalServerErrorException
453 * @throws NotFoundException
454 * @throws UnauthorizedException
456 function prepare_photo_data($type, $scale, $photo_id, $uid)
458 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
459 $data_sql = ($scale === false ? "" : "data, ");
461 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
462 // clients needs to convert this in their way for further processing
463 $r = DBA::toArray(DBA::p(
464 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
465 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
466 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
467 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
468 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
469 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
475 'image/jpeg' => 'jpg',
476 'image/png' => 'png',
480 // prepare output data for photo
481 if (DBA::isResult($r)) {
482 $data = ['photo' => $r[0]];
483 $data['photo']['id'] = $data['photo']['resource-id'];
484 if ($scale !== false) {
485 $data['photo']['data'] = base64_encode($data['photo']['data']);
487 unset($data['photo']['datasize']); //needed only with scale param
489 if ($type == "xml") {
490 $data['photo']['links'] = [];
491 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
492 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
494 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
497 $data['photo']['link'] = [];
498 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
500 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
501 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
505 unset($data['photo']['resource-id']);
506 unset($data['photo']['minscale']);
507 unset($data['photo']['maxscale']);
509 throw new NotFoundException();
512 // retrieve item element for getting activities (like, dislike etc.) related to photo
513 $condition = ['uid' => $uid, 'resource-id' => $photo_id];
514 $item = Post::selectFirst(['id', 'uid', 'uri', 'uri-id', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
515 if (!DBA::isResult($item)) {
516 throw new NotFoundException('Photo-related item not found.');
519 $data['photo']['friendica_activities'] = DI::friendicaActivities()->createFromUriId($item['uri-id'], $item['uid'], $type);
521 // retrieve comments on photo
522 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
523 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
525 $statuses = Post::selectForUser($uid, [], $condition);
527 // prepare output of comments
529 while ($status = DBA::fetch($statuses)) {
530 $commentData[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'])->toArray();
532 DBA::close($statuses);
535 if ($type == "xml") {
537 foreach ($commentData as $comment) {
538 $comments[$k++ . ":comment"] = $comment;
541 foreach ($commentData as $comment) {
542 $comments[] = $comment;
545 $data['photo']['friendica_comments'] = $comments;
547 // include info if rights on photo and rights on item are mismatching
548 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
549 $data['photo']['deny_cid'] != $item['deny_cid'] ||
550 $data['photo']['allow_gid'] != $item['allow_gid'] ||
551 $data['photo']['deny_gid'] != $item['deny_gid'];
552 $data['photo']['rights_mismatch'] = $rights_mismatch;
559 * @param string $text
562 * @throws InternalServerErrorException
564 function api_clean_plain_items($text)
566 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
568 $text = BBCode::cleanPictureLinks($text);
569 $URLSearchString = "^\[\]";
571 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
573 if ($include_entities == "true") {
574 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
577 // Simplify "attachment" element
578 $text = BBCode::removeAttachment($text);
584 * Add a new group to the database.
586 * @param string $name Group name
587 * @param int $uid User ID
588 * @param array $users List of users to add to the group
591 * @throws BadRequestException
593 function group_create($name, $uid, $users = [])
595 // error if no name specified
597 throw new BadRequestException('group name not specified');
600 // error message if specified group name already exists
601 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
602 throw new BadRequestException('group name already exists');
605 // Check if the group needs to be reactivated
606 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
607 $reactivate_group = true;
611 $ret = Group::create($uid, $name);
613 $gid = Group::getIdByName($uid, $name);
615 throw new BadRequestException('other API error');
619 $erroraddinguser = false;
621 foreach ($users as $user) {
623 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
624 Group::addMember($gid, $cid);
626 $erroraddinguser = true;
627 $errorusers[] = $cid;
631 // return success message incl. missing users in array
632 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
634 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
642 * Returns all lists the user subscribes to.
644 * @param string $type Return type (atom, rss, xml, json)
646 * @return array|string
647 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
649 function api_lists_list($type)
651 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
653 /// @TODO $ret is not filled here?
654 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
657 api_register_func('api/lists/list', 'api_lists_list', true);
658 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
661 * Returns all groups the user owns.
663 * @param string $type Return type (atom, rss, xml, json)
665 * @return array|string
666 * @throws BadRequestException
667 * @throws ForbiddenException
668 * @throws ImagickException
669 * @throws InternalServerErrorException
670 * @throws UnauthorizedException
671 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
673 function api_lists_ownerships($type)
675 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
676 $uid = BaseApi::getCurrentUserID();
679 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
681 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
683 // loop through all groups
685 foreach ($groups as $group) {
686 if ($group['visible']) {
692 'name' => $group['name'],
693 'id' => intval($group['id']),
694 'id_str' => (string) $group['id'],
695 'user' => $user_info,
699 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
702 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
705 * Sends a new direct message.
707 * @param string $type Return type (atom, rss, xml, json)
709 * @return array|string
710 * @throws BadRequestException
711 * @throws ForbiddenException
712 * @throws ImagickException
713 * @throws InternalServerErrorException
714 * @throws NotFoundException
715 * @throws UnauthorizedException
716 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
718 function api_direct_messages_new($type)
720 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
721 $uid = BaseApi::getCurrentUserID();
723 if (empty($_POST["text"]) || empty($_REQUEST['screen_name']) && empty($_REQUEST['user_id'])) {
727 $sender = DI::twitterUser()->createFromUserId($uid, true)->toArray();
729 $cid = BaseApi::getContactIDForSearchterm($_REQUEST['screen_name'] ?? '', $_REQUEST['profileurl'] ?? '', $_REQUEST['user_id'] ?? 0, 0);
731 throw new NotFoundException('Recipient not found');
735 if (!empty($_REQUEST['replyto'])) {
736 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
737 $replyto = $mail['parent-uri'];
738 $sub = $mail['title'];
740 if (!empty($_REQUEST['title'])) {
741 $sub = $_REQUEST['title'];
743 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
747 $cdata = Contact::getPublicAndUserContactID($cid, $uid);
749 $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
752 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
753 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid, true)->toArray(), $sender);
755 $ret = ["error" => $id];
758 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
761 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true);
764 * delete a direct_message from mail table through api
766 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
767 * @return string|array
768 * @throws BadRequestException
769 * @throws ForbiddenException
770 * @throws ImagickException
771 * @throws InternalServerErrorException
772 * @throws UnauthorizedException
773 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
775 function api_direct_messages_destroy($type)
777 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
778 $uid = BaseApi::getCurrentUserID();
781 $id = $_REQUEST['id'] ?? 0;
783 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
784 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
785 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
787 // error if no id or parenturi specified (for clients posting parent-uri as well)
788 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
789 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
790 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
793 // BadRequestException if no id specified (for clients using Twitter API)
795 throw new BadRequestException('Message id not specified');
798 // add parent-uri to sql command if specified by calling app
799 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
801 // error message if specified id is not in database
802 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
803 if ($verbose == "true") {
804 $answer = ['result' => 'error', 'message' => 'message id not in database'];
805 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
807 /// @todo BadRequestException ok for Twitter API clients?
808 throw new BadRequestException('message id not in database');
812 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
814 if ($verbose == "true") {
817 $answer = ['result' => 'ok', 'message' => 'message deleted'];
818 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
820 $answer = ['result' => 'error', 'message' => 'unknown error'];
821 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
824 /// @todo return JSON data like Twitter API not yet implemented
827 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true);
831 * @param string $type Return type (atom, rss, xml, json)
833 * @param string $verbose
835 * @return array|string
836 * @throws BadRequestException
837 * @throws ForbiddenException
838 * @throws ImagickException
839 * @throws InternalServerErrorException
840 * @throws UnauthorizedException
842 function api_direct_messages_box($type, $box, $verbose)
844 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
845 $uid = BaseApi::getCurrentUserID();
848 $count = $_GET['count'] ?? 20;
849 $page = $_REQUEST['page'] ?? 1;
851 $since_id = $_REQUEST['since_id'] ?? 0;
852 $max_id = $_REQUEST['max_id'] ?? 0;
854 $user_id = $_REQUEST['user_id'] ?? '';
855 $screen_name = $_REQUEST['screen_name'] ?? '';
857 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
859 $profile_url = $user_info["url"];
862 $start = max(0, ($page - 1) * $count);
867 if ($box=="sentbox") {
868 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
869 } elseif ($box == "conversation") {
870 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
871 } elseif ($box == "all") {
873 } elseif ($box == "inbox") {
874 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
878 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
881 if ($user_id != "") {
882 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
883 } elseif ($screen_name !="") {
884 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
887 $r = DBA::toArray(DBA::p(
888 "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 ?,?",
894 if ($verbose == "true" && !DBA::isResult($r)) {
895 $answer = ['result' => 'error', 'message' => 'no mails available'];
896 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
900 foreach ($r as $item) {
901 if ($box == "inbox" || $item['from-url'] != $profile_url) {
902 $recipient = $user_info;
903 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
904 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
905 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
906 $sender = $user_info;
909 if (isset($recipient) && isset($sender)) {
910 $ret[] = api_format_messages($item, $recipient, $sender);
914 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
918 * Returns the most recent direct messages sent by the user.
920 * @param string $type Return type (atom, rss, xml, json)
922 * @return array|string
923 * @throws BadRequestException
924 * @throws ForbiddenException
925 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
927 function api_direct_messages_sentbox($type)
929 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
930 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
931 return api_direct_messages_box($type, "sentbox", $verbose);
934 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
937 * Returns the most recent direct messages sent to the user.
939 * @param string $type Return type (atom, rss, xml, json)
941 * @return array|string
942 * @throws BadRequestException
943 * @throws ForbiddenException
944 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
946 function api_direct_messages_inbox($type)
948 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
949 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
950 return api_direct_messages_box($type, "inbox", $verbose);
953 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
957 * @param string $type Return type (atom, rss, xml, json)
959 * @return array|string
960 * @throws BadRequestException
961 * @throws ForbiddenException
963 function api_direct_messages_all($type)
965 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
966 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
967 return api_direct_messages_box($type, "all", $verbose);
970 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
974 * @param string $type Return type (atom, rss, xml, json)
976 * @return array|string
977 * @throws BadRequestException
978 * @throws ForbiddenException
980 function api_direct_messages_conversation($type)
982 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
983 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
984 return api_direct_messages_box($type, "conversation", $verbose);
987 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
990 * list all photos of the authenticated user
992 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
993 * @return string|array
994 * @throws ForbiddenException
995 * @throws InternalServerErrorException
997 function api_fr_photos_list($type)
999 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1000 $uid = BaseApi::getCurrentUserID();
1002 $r = DBA::toArray(DBA::p(
1003 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
1004 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
1005 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
1006 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
1009 'image/jpeg' => 'jpg',
1010 'image/png' => 'png',
1011 'image/gif' => 'gif'
1013 $data = ['photo'=>[]];
1014 if (DBA::isResult($r)) {
1015 foreach ($r as $rr) {
1017 $photo['id'] = $rr['resource-id'];
1018 $photo['album'] = $rr['album'];
1019 $photo['filename'] = $rr['filename'];
1020 $photo['type'] = $rr['type'];
1021 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
1022 $photo['created'] = $rr['created'];
1023 $photo['edited'] = $rr['edited'];
1024 $photo['desc'] = $rr['desc'];
1026 if ($type == "xml") {
1027 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
1029 $photo['thumb'] = $thumb;
1030 $data['photo'][] = $photo;
1034 return DI::apiResponse()->formatData("photos", $type, $data);
1037 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
1040 * upload a new photo or change an existing photo
1042 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1043 * @return string|array
1044 * @throws BadRequestException
1045 * @throws ForbiddenException
1046 * @throws ImagickException
1047 * @throws InternalServerErrorException
1048 * @throws NotFoundException
1050 function api_fr_photo_create_update($type)
1052 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1053 $uid = BaseApi::getCurrentUserID();
1056 $photo_id = $_REQUEST['photo_id'] ?? null;
1057 $desc = $_REQUEST['desc'] ?? null;
1058 $album = $_REQUEST['album'] ?? null;
1059 $album_new = $_REQUEST['album_new'] ?? null;
1060 $allow_cid = $_REQUEST['allow_cid'] ?? null;
1061 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
1062 $allow_gid = $_REQUEST['allow_gid'] ?? null;
1063 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
1064 // Pictures uploaded via API never get posted as a visible status
1065 // See https://github.com/friendica/friendica/issues/10990
1066 $visibility = false;
1068 // do several checks on input parameters
1069 // we do not allow calls without album string
1070 if ($album == null) {
1071 throw new BadRequestException("no albumname specified");
1073 // if photo_id == null --> we are uploading a new photo
1074 if ($photo_id == null) {
1077 // error if no media posted in create-mode
1078 if (empty($_FILES['media'])) {
1080 throw new BadRequestException("no media data submitted");
1083 // album_new will be ignored in create-mode
1088 // check if photo is existing in databasei
1089 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
1090 throw new BadRequestException("photo not available");
1094 // checks on acl strings provided by clients
1095 $acl_input_error = false;
1096 $acl_input_error |= check_acl_input($allow_cid, $uid);
1097 $acl_input_error |= check_acl_input($deny_cid, $uid);
1098 $acl_input_error |= check_acl_input($allow_gid, $uid);
1099 $acl_input_error |= check_acl_input($deny_gid, $uid);
1100 if ($acl_input_error) {
1101 throw new BadRequestException("acl data invalid");
1103 // now let's upload the new media in create-mode
1104 if ($mode == "create") {
1105 $media = $_FILES['media'];
1106 $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);
1108 // return success of updating or error message
1109 if (!is_null($data)) {
1110 return DI::apiResponse()->formatData("photo_create", $type, $data);
1112 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
1116 // now let's do the changes in update-mode
1117 if ($mode == "update") {
1118 $updated_fields = [];
1120 if (!is_null($desc)) {
1121 $updated_fields['desc'] = $desc;
1124 if (!is_null($album_new)) {
1125 $updated_fields['album'] = $album_new;
1128 if (!is_null($allow_cid)) {
1129 $allow_cid = trim($allow_cid);
1130 $updated_fields['allow_cid'] = $allow_cid;
1133 if (!is_null($deny_cid)) {
1134 $deny_cid = trim($deny_cid);
1135 $updated_fields['deny_cid'] = $deny_cid;
1138 if (!is_null($allow_gid)) {
1139 $allow_gid = trim($allow_gid);
1140 $updated_fields['allow_gid'] = $allow_gid;
1143 if (!is_null($deny_gid)) {
1144 $deny_gid = trim($deny_gid);
1145 $updated_fields['deny_gid'] = $deny_gid;
1149 if (count($updated_fields) > 0) {
1150 $nothingtodo = false;
1151 $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
1153 $nothingtodo = true;
1156 if (!empty($_FILES['media'])) {
1157 $nothingtodo = false;
1158 $media = $_FILES['media'];
1159 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
1160 if (!is_null($data)) {
1161 return DI::apiResponse()->formatData("photo_update", $type, $data);
1165 // return success of updating or error message
1167 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
1168 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1171 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
1172 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1174 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
1177 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
1180 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true);
1181 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true);
1184 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
1186 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1187 * @return string|array
1188 * @throws BadRequestException
1189 * @throws ForbiddenException
1190 * @throws InternalServerErrorException
1191 * @throws NotFoundException
1193 function api_fr_photo_detail($type)
1195 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1196 $uid = BaseApi::getCurrentUserID();
1198 if (empty($_REQUEST['photo_id'])) {
1199 throw new BadRequestException("No photo id.");
1202 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
1203 $photo_id = $_REQUEST['photo_id'];
1205 // prepare json/xml output with data from database for the requested photo
1206 $data = prepare_photo_data($type, $scale, $photo_id, $uid);
1208 return DI::apiResponse()->formatData("photo_detail", $type, $data);
1211 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
1214 * updates the profile image for the user (either a specified profile or the default profile)
1216 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1218 * @return string|array
1219 * @throws BadRequestException
1220 * @throws ForbiddenException
1221 * @throws ImagickException
1222 * @throws InternalServerErrorException
1223 * @throws NotFoundException
1224 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
1226 function api_account_update_profile_image($type)
1228 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1229 $uid = BaseApi::getCurrentUserID();
1232 $profile_id = $_REQUEST['profile_id'] ?? 0;
1234 // error if image data is missing
1235 if (empty($_FILES['image'])) {
1236 throw new BadRequestException("no media data submitted");
1239 // check if specified profile id is valid
1240 if ($profile_id != 0) {
1241 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
1242 // error message if specified profile id is not in database
1243 if (!DBA::isResult($profile)) {
1244 throw new BadRequestException("profile_id not available");
1246 $is_default_profile = $profile['is-default'];
1248 $is_default_profile = 1;
1251 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
1253 if (!empty($_FILES['image'])) {
1254 $media = $_FILES['image'];
1255 } elseif (!empty($_FILES['media'])) {
1256 $media = $_FILES['media'];
1258 // save new profile image
1259 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
1262 if (is_array($media['type'])) {
1263 $filetype = $media['type'][0];
1265 $filetype = $media['type'];
1267 if ($filetype == "image/jpeg") {
1269 } elseif ($filetype == "image/png") {
1272 throw new InternalServerErrorException('Unsupported filetype');
1275 // change specified profile or all profiles to the new resource-id
1276 if ($is_default_profile) {
1277 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
1278 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
1280 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
1281 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
1282 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
1285 Contact::updateSelfFromUserID($uid, true);
1287 // Update global directory in background
1288 Profile::publishUpdate($uid);
1290 // output for client
1292 $skip_status = $_REQUEST['skip_status'] ?? false;
1294 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
1296 // "verified" isn't used here in the standard
1297 unset($user_info["verified"]);
1299 // "uid" is only needed for some internal stuff, so remove it from here
1300 unset($user_info['uid']);
1302 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
1304 // SaveMediaToDatabase failed for some reason
1305 throw new InternalServerErrorException("image upload failed");
1309 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true);
1312 * Return all or a specified group of the user with the containing contacts.
1314 * @param string $type Return type (atom, rss, xml, json)
1316 * @return array|string
1317 * @throws BadRequestException
1318 * @throws ForbiddenException
1319 * @throws ImagickException
1320 * @throws InternalServerErrorException
1321 * @throws UnauthorizedException
1323 function api_friendica_group_show($type)
1325 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1326 $uid = BaseApi::getCurrentUserID();
1329 $gid = $_REQUEST['gid'] ?? 0;
1331 // get data of the specified group id or all groups if not specified
1333 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
1335 // error message if specified gid is not in database
1336 if (!DBA::isResult($groups)) {
1337 throw new BadRequestException("gid not available");
1340 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
1343 // loop through all groups and retrieve all members for adding data in the user array
1345 foreach ($groups as $rr) {
1346 $members = Contact\Group::getById($rr['id']);
1349 if ($type == "xml") {
1350 $user_element = "users";
1352 foreach ($members as $member) {
1353 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
1354 $users[$k++.":user"] = $user;
1357 $user_element = "user";
1358 foreach ($members as $member) {
1359 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
1363 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
1365 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
1368 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
1373 * @param string $type Return type (atom, rss, xml, json)
1375 * @return array|string
1376 * @throws BadRequestException
1377 * @throws ForbiddenException
1378 * @throws ImagickException
1379 * @throws InternalServerErrorException
1380 * @throws UnauthorizedException
1381 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
1383 function api_lists_destroy($type)
1385 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1386 $uid = BaseApi::getCurrentUserID();
1389 $gid = $_REQUEST['list_id'] ?? 0;
1391 // error if no gid specified
1393 throw new BadRequestException('gid not specified');
1396 // get data of the specified group id
1397 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1398 // error message if specified gid is not in database
1400 throw new BadRequestException('gid not available');
1403 if (Group::remove($gid)) {
1405 'name' => $group['name'],
1406 'id' => intval($gid),
1407 'id_str' => (string) $gid,
1408 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1411 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1415 api_register_func('api/lists/destroy', 'api_lists_destroy', true);
1418 * Create the specified group with the posted array of contacts.
1420 * @param string $type Return type (atom, rss, xml, json)
1422 * @return array|string
1423 * @throws BadRequestException
1424 * @throws ForbiddenException
1425 * @throws ImagickException
1426 * @throws InternalServerErrorException
1427 * @throws UnauthorizedException
1429 function api_friendica_group_create($type)
1431 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1432 $uid = BaseApi::getCurrentUserID();
1435 $name = $_REQUEST['name'] ?? '';
1436 $json = json_decode($_POST['json'], true);
1437 $users = $json['user'];
1439 $success = group_create($name, $uid, $users);
1441 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
1444 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true);
1447 * Create a new group.
1449 * @param string $type Return type (atom, rss, xml, json)
1451 * @return array|string
1452 * @throws BadRequestException
1453 * @throws ForbiddenException
1454 * @throws ImagickException
1455 * @throws InternalServerErrorException
1456 * @throws UnauthorizedException
1457 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
1459 function api_lists_create($type)
1461 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1462 $uid = BaseApi::getCurrentUserID();
1465 $name = $_REQUEST['name'] ?? '';
1467 $success = group_create($name, $uid);
1468 if ($success['success']) {
1470 'name' => $success['name'],
1471 'id' => intval($success['gid']),
1472 'id_str' => (string) $success['gid'],
1473 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1476 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
1480 api_register_func('api/lists/create', 'api_lists_create', true);
1483 * Update information about a group.
1485 * @param string $type Return type (atom, rss, xml, json)
1487 * @return array|string
1488 * @throws BadRequestException
1489 * @throws ForbiddenException
1490 * @throws ImagickException
1491 * @throws InternalServerErrorException
1492 * @throws UnauthorizedException
1493 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
1495 function api_lists_update($type)
1497 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1498 $uid = BaseApi::getCurrentUserID();
1501 $gid = $_REQUEST['list_id'] ?? 0;
1502 $name = $_REQUEST['name'] ?? '';
1504 // error if no gid specified
1506 throw new BadRequestException('gid not specified');
1509 // get data of the specified group id
1510 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1511 // error message if specified gid is not in database
1513 throw new BadRequestException('gid not available');
1516 if (Group::update($gid, $name)) {
1519 'id' => intval($gid),
1520 'id_str' => (string) $gid,
1521 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1524 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1528 api_register_func('api/lists/update', 'api_lists_update', true);
1531 * search for direct_messages containing a searchstring through api
1533 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1534 * @param string $box
1535 * @return string|array (success: success=true if found and search_result contains found messages,
1536 * success=false if nothing was found, search_result='nothing found',
1537 * error: result=error with error message)
1538 * @throws BadRequestException
1539 * @throws ForbiddenException
1540 * @throws ImagickException
1541 * @throws InternalServerErrorException
1542 * @throws UnauthorizedException
1544 function api_friendica_direct_messages_search($type, $box = "")
1546 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1547 $uid = BaseApi::getCurrentUserID();
1550 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1551 $searchstring = $_REQUEST['searchstring'] ?? '';
1553 // error if no searchstring specified
1554 if ($searchstring == "") {
1555 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
1556 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
1559 // get data for the specified searchstring
1560 $r = DBA::toArray(DBA::p(
1561 "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",
1563 '%'.$searchstring.'%'
1566 $profile_url = $user_info["url"];
1568 // message if nothing was found
1569 if (!DBA::isResult($r)) {
1570 $success = ['success' => false, 'search_results' => 'problem with query'];
1571 } elseif (count($r) == 0) {
1572 $success = ['success' => false, 'search_results' => 'nothing found'];
1575 foreach ($r as $item) {
1576 if ($box == "inbox" || $item['from-url'] != $profile_url) {
1577 $recipient = $user_info;
1578 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1579 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
1580 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1581 $sender = $user_info;
1584 if (isset($recipient) && isset($sender)) {
1585 $ret[] = api_format_messages($item, $recipient, $sender);
1588 $success = ['success' => true, 'search_results' => $ret];
1591 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
1594 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);