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\TooManyRequestsException;
48 use Friendica\Network\HTTPException\UnauthorizedException;
49 use Friendica\Object\Image;
50 use Friendica\Util\DateTimeFormat;
51 use Friendica\Util\Images;
52 use Friendica\Util\Strings;
54 require_once __DIR__ . '/../mod/item.php';
59 * Register a function to be the endpoint for defined API path.
61 * @param string $path API URL path, relative to DI::baseUrl()
62 * @param string $func Function name to call on path request
64 function api_register_func($path, $func)
72 // Workaround for hotot
73 $path = str_replace("api/", "api/1.1/", $path);
81 * Main API entry point
83 * Authenticate user, call registered API function, set HTTP headers
85 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
86 * @return string|array API call result
89 function api_call($command, $extension)
93 Logger::info('Legacy API call', ['command' => $command, 'extension' => $extension]);
96 foreach ($API as $p => $info) {
97 if (strpos($command, $p) === 0) {
98 Logger::debug(BaseApi::LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
100 $stamp = microtime(true);
101 $return = call_user_func($info['func'], $extension);
102 $duration = floatval(microtime(true) - $stamp);
104 Logger::info(BaseApi::LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
106 DI::profiler()->saveLog(DI::logger(), BaseApi::LOG_PREFIX . 'performance');
108 if (false === $return) {
110 * api function returned false withour throw an
111 * exception. This should not happend, throw a 500
113 throw new InternalServerErrorException();
116 switch ($extension) {
118 header("Content-Type: text/xml");
121 header("Content-Type: application/json");
122 if (!empty($return)) {
123 $json = json_encode(end($return));
124 if (!empty($_GET['callback'])) {
125 $json = $_GET['callback'] . "(" . $json . ")";
131 header("Content-Type: application/rss+xml");
132 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
135 header("Content-Type: application/atom+xml");
136 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
143 Logger::warning(BaseApi::LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
144 throw new NotFoundException();
145 } catch (HTTPException $e) {
146 Logger::notice(BaseApi::LOG_PREFIX . 'got exception', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString(), 'error' => $e]);
147 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $extension);
154 * @param array $recipient
155 * @param array $sender
158 * @throws InternalServerErrorException
160 function api_format_messages($item, $recipient, $sender)
162 // standard meta information
165 'sender_id' => $sender['id'],
167 'recipient_id' => $recipient['id'],
168 'created_at' => DateTimeFormat::utc($item['created'] ?? 'now', DateTimeFormat::API),
169 'sender_screen_name' => $sender['screen_name'],
170 'recipient_screen_name' => $recipient['screen_name'],
172 'recipient' => $recipient,
174 'friendica_seen' => $item['seen'] ?? 0,
175 'friendica_parent_uri' => $item['parent-uri'] ?? '',
178 // "uid" is only needed for some internal stuff, so remove it from here
179 if (isset($ret['sender']['uid'])) {
180 unset($ret['sender']['uid']);
182 if (isset($ret['recipient']['uid'])) {
183 unset($ret['recipient']['uid']);
186 //don't send title to regular StatusNET requests to avoid confusing these apps
187 if (!empty($_GET['getText'])) {
188 $ret['title'] = $item['title'];
189 if ($_GET['getText'] == 'html') {
190 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
191 } elseif ($_GET['getText'] == 'plain') {
192 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
195 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
197 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
198 unset($ret['sender']);
199 unset($ret['recipient']);
207 * @param string $acl_string
212 function check_acl_input($acl_string, $uid)
214 if (empty($acl_string)) {
218 $contact_not_found = false;
220 // split <x><y><z> into array of cid's
221 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
223 // check for each cid if it is available on server
224 $cid_array = $array[0];
225 foreach ($cid_array as $cid) {
226 $cid = str_replace("<", "", $cid);
227 $cid = str_replace(">", "", $cid);
228 $condition = ['id' => $cid, 'uid' => $uid];
229 $contact_not_found |= !DBA::exists('contact', $condition);
231 return $contact_not_found;
235 * @param string $mediatype
236 * @param array $media
237 * @param string $type
238 * @param string $album
239 * @param string $allow_cid
240 * @param string $deny_cid
241 * @param string $allow_gid
242 * @param string $deny_gid
243 * @param string $desc
244 * @param integer $phototype
245 * @param boolean $visibility
246 * @param string $photo_id
249 * @throws BadRequestException
250 * @throws ForbiddenException
251 * @throws ImagickException
252 * @throws InternalServerErrorException
253 * @throws NotFoundException
254 * @throws UnauthorizedException
256 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype, $visibility, $photo_id, $uid)
264 if (is_array($media)) {
265 if (is_array($media['tmp_name'])) {
266 $src = $media['tmp_name'][0];
268 $src = $media['tmp_name'];
270 if (is_array($media['name'])) {
271 $filename = basename($media['name'][0]);
273 $filename = basename($media['name']);
275 if (is_array($media['size'])) {
276 $filesize = intval($media['size'][0]);
278 $filesize = intval($media['size']);
280 if (is_array($media['type'])) {
281 $filetype = $media['type'][0];
283 $filetype = $media['type'];
287 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
290 "File upload src: " . $src . " - filename: " . $filename .
291 " - size: " . $filesize . " - type: " . $filetype);
293 // check if there was a php upload error
294 if ($filesize == 0 && $media['error'] == 1) {
295 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
297 // check against max upload size within Friendica instance
298 $maximagesize = DI::config()->get('system', 'maximagesize');
299 if ($maximagesize && ($filesize > $maximagesize)) {
300 $formattedBytes = Strings::formatBytes($maximagesize);
301 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
304 // create Photo instance with the data of the image
305 $imagedata = @file_get_contents($src);
306 $Image = new Image($imagedata, $filetype);
307 if (!$Image->isValid()) {
308 throw new InternalServerErrorException("unable to process image data");
311 // check orientation of image
312 $Image->orient($src);
315 // check max length of images on server
316 $max_length = DI::config()->get('system', 'max_image_length');
317 if ($max_length > 0) {
318 $Image->scaleDown($max_length);
319 logger::info("File upload: Scaling picture to new size " . $max_length);
321 $width = $Image->getWidth();
322 $height = $Image->getHeight();
324 // create a new resource-id if not already provided
325 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
327 if ($mediatype == "photo") {
328 // upload normal image (scales 0, 1, 2)
329 logger::info("photo upload: starting new photo upload");
331 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
333 logger::notice("photo upload: image upload with scale 0 (original size) failed");
335 if ($width > 640 || $height > 640) {
336 $Image->scaleDown(640);
337 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
339 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
343 if ($width > 320 || $height > 320) {
344 $Image->scaleDown(320);
345 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
347 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
350 logger::info("photo upload: new photo upload ended");
351 } elseif ($mediatype == "profileimage") {
352 // upload profile image (scales 4, 5, 6)
353 logger::info("photo upload: starting new profile image upload");
355 if ($width > 300 || $height > 300) {
356 $Image->scaleDown(300);
357 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
359 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
363 if ($width > 80 || $height > 80) {
364 $Image->scaleDown(80);
365 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
367 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
371 if ($width > 48 || $height > 48) {
372 $Image->scaleDown(48);
373 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
375 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
378 $Image->__destruct();
379 logger::info("photo upload: new profile image upload ended");
383 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
384 if ($photo_id == null && $mediatype == "photo") {
385 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid);
387 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
388 return prepare_photo_data($type, false, $resource_id, $uid);
390 throw new InternalServerErrorException("image upload failed");
391 DI::page()->exit(DI::apiResponse());
397 * @param string $hash
398 * @param string $allow_cid
399 * @param string $deny_cid
400 * @param string $allow_gid
401 * @param string $deny_gid
402 * @param string $filetype
403 * @param boolean $visibility
405 * @throws InternalServerErrorException
407 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid)
409 // get data about the api authenticated user
410 $uri = Item::newURI(intval($uid));
411 $owner_record = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
414 $arr['guid'] = System::createUUID();
415 $arr['uid'] = intval($uid);
417 $arr['type'] = 'photo';
419 $arr['resource-id'] = $hash;
420 $arr['contact-id'] = $owner_record['id'];
421 $arr['owner-name'] = $owner_record['name'];
422 $arr['owner-link'] = $owner_record['url'];
423 $arr['owner-avatar'] = $owner_record['thumb'];
424 $arr['author-name'] = $owner_record['name'];
425 $arr['author-link'] = $owner_record['url'];
426 $arr['author-avatar'] = $owner_record['thumb'];
428 $arr['allow_cid'] = $allow_cid;
429 $arr['allow_gid'] = $allow_gid;
430 $arr['deny_cid'] = $deny_cid;
431 $arr['deny_gid'] = $deny_gid;
432 $arr['visible'] = $visibility;
436 'image/jpeg' => 'jpg',
437 'image/png' => 'png',
441 // adds link to the thumbnail scale photo
442 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
443 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
446 // do the magic for storing the item in the database and trigger the federation to other contacts
452 * @param string $type
454 * @param string $photo_id
457 * @throws BadRequestException
458 * @throws ForbiddenException
459 * @throws ImagickException
460 * @throws InternalServerErrorException
461 * @throws NotFoundException
462 * @throws UnauthorizedException
464 function prepare_photo_data($type, $scale, $photo_id, $uid)
466 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
467 $data_sql = ($scale === false ? "" : "data, ");
469 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
470 // clients needs to convert this in their way for further processing
471 $r = DBA::toArray(DBA::p(
472 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
473 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
474 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
475 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
476 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
477 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
483 'image/jpeg' => 'jpg',
484 'image/png' => 'png',
488 // prepare output data for photo
489 if (DBA::isResult($r)) {
490 $data = ['photo' => $r[0]];
491 $data['photo']['id'] = $data['photo']['resource-id'];
492 if ($scale !== false) {
493 $data['photo']['data'] = base64_encode($data['photo']['data']);
495 unset($data['photo']['datasize']); //needed only with scale param
497 if ($type == "xml") {
498 $data['photo']['links'] = [];
499 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
500 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
502 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
505 $data['photo']['link'] = [];
506 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
508 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
509 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
513 unset($data['photo']['resource-id']);
514 unset($data['photo']['minscale']);
515 unset($data['photo']['maxscale']);
517 throw new NotFoundException();
520 // retrieve item element for getting activities (like, dislike etc.) related to photo
521 $condition = ['uid' => $uid, 'resource-id' => $photo_id];
522 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
523 if (!DBA::isResult($item)) {
524 throw new NotFoundException('Photo-related item not found.');
527 $data['photo']['friendica_activities'] = DI::friendicaActivities()->createFromUriId($item['uri-id'], $item['uid'], $type);
529 // retrieve comments on photo
530 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
531 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
533 $statuses = Post::selectForUser($uid, [], $condition);
535 // prepare output of comments
537 while ($status = DBA::fetch($statuses)) {
538 $commentData[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'])->toArray();
540 DBA::close($statuses);
543 if ($type == "xml") {
545 foreach ($commentData as $comment) {
546 $comments[$k++ . ":comment"] = $comment;
549 foreach ($commentData as $comment) {
550 $comments[] = $comment;
553 $data['photo']['friendica_comments'] = $comments;
555 // include info if rights on photo and rights on item are mismatching
556 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
557 $data['photo']['deny_cid'] != $item['deny_cid'] ||
558 $data['photo']['allow_gid'] != $item['allow_gid'] ||
559 $data['photo']['deny_gid'] != $item['deny_gid'];
560 $data['photo']['rights_mismatch'] = $rights_mismatch;
567 * @param string $text
570 * @throws InternalServerErrorException
572 function api_clean_plain_items($text)
574 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
576 $text = BBCode::cleanPictureLinks($text);
577 $URLSearchString = "^\[\]";
579 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
581 if ($include_entities == "true") {
582 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
585 // Simplify "attachment" element
586 $text = BBCode::removeAttachment($text);
592 * Add a new group to the database.
594 * @param string $name Group name
595 * @param int $uid User ID
596 * @param array $users List of users to add to the group
599 * @throws BadRequestException
601 function group_create($name, $uid, $users = [])
603 // error if no name specified
605 throw new BadRequestException('group name not specified');
608 // error message if specified group name already exists
609 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
610 throw new BadRequestException('group name already exists');
613 // Check if the group needs to be reactivated
614 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
615 $reactivate_group = true;
619 $ret = Group::create($uid, $name);
621 $gid = Group::getIdByName($uid, $name);
623 throw new BadRequestException('other API error');
627 $erroraddinguser = false;
629 foreach ($users as $user) {
631 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
632 Group::addMember($gid, $cid);
634 $erroraddinguser = true;
635 $errorusers[] = $cid;
639 // return success message incl. missing users in array
640 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
642 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
650 * Updates the user’s current status.
652 * @param string $type Return type (atom, rss, xml, json)
654 * @return array|string
655 * @throws BadRequestException
656 * @throws ForbiddenException
657 * @throws ImagickException
658 * @throws InternalServerErrorException
659 * @throws TooManyRequestsException
660 * @throws UnauthorizedException
661 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
663 function api_statuses_update($type)
665 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
666 $uid = BaseApi::getCurrentUserID();
670 // convert $_POST array items to the form we use for web posts.
671 if (!empty($_REQUEST['htmlstatus'])) {
672 $txt = $_REQUEST['htmlstatus'];
673 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
674 $txt = HTML::toBBCodeVideo($txt);
676 $config = HTMLPurifier_Config::createDefault();
677 $config->set('Cache.DefinitionImpl', null);
679 $purifier = new HTMLPurifier($config);
680 $txt = $purifier->purify($txt);
682 $_REQUEST['body'] = HTML::toBBCode($txt);
685 $_REQUEST['body'] = $_REQUEST['status'] ?? null;
688 $_REQUEST['title'] = $_REQUEST['title'] ?? null;
690 $parent = $_REQUEST['in_reply_to_status_id'] ?? null;
692 // Twidere sends "-1" if it is no reply ...
697 if (ctype_digit($parent)) {
698 $_REQUEST['parent'] = $parent;
700 $_REQUEST['parent_uri'] = $parent;
703 if (!empty($_REQUEST['lat']) && !empty($_REQUEST['long'])) {
704 $_REQUEST['coord'] = sprintf("%s %s", $_REQUEST['lat'], $_REQUEST['long']);
706 $_REQUEST['profile_uid'] = $uid;
709 // Check for throttling (maximum posts per day, week and month)
710 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
711 if ($throttle_day > 0) {
712 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
714 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
715 $posts_day = Post::count($condition);
717 if ($posts_day > $throttle_day) {
718 logger::info('Daily posting limit reached for user ' . $uid);
719 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
720 throw new TooManyRequestsException(DI::l10n()->tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
724 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
725 if ($throttle_week > 0) {
726 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
728 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
729 $posts_week = Post::count($condition);
731 if ($posts_week > $throttle_week) {
732 logger::info('Weekly posting limit reached for user ' . $uid);
733 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
734 throw new TooManyRequestsException(DI::l10n()->tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
738 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
739 if ($throttle_month > 0) {
740 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
742 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
743 $posts_month = Post::count($condition);
745 if ($posts_month > $throttle_month) {
746 logger::info('Monthly posting limit reached for user ' . $uid);
747 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
748 throw new TooManyRequestsException(DI::l10n()->t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
753 if (!empty($_REQUEST['media_ids'])) {
754 $ids = explode(',', $_REQUEST['media_ids']);
755 } elseif (!empty($_FILES['media'])) {
756 // upload the image if we have one
757 $picture = Photo::upload($uid, $_FILES['media']);
758 if (is_array($picture)) {
759 $ids[] = $picture['id'];
767 foreach ($ids as $id) {
768 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
769 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
770 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
771 ORDER BY `photo`.`width` DESC LIMIT 2", $id, $uid));
773 if (!empty($media)) {
774 $ressources[] = $media[0]['resource-id'];
775 $phototypes = Images::supportedTypes();
776 $ext = $phototypes[$media[0]['type']];
778 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
779 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
780 'size' => $media[0]['datasize'],
781 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
782 'description' => $media[0]['desc'] ?? '',
783 'width' => $media[0]['width'],
784 'height' => $media[0]['height']];
786 if (count($media) > 1) {
787 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
788 $attachment['preview-width'] = $media[1]['width'];
789 $attachment['preview-height'] = $media[1]['height'];
791 $attachments[] = $attachment;
795 // We have to avoid that the post is rejected because of an empty body
796 if (empty($_REQUEST['body'])) {
797 $_REQUEST['body'] = '[hr]';
801 if (!empty($attachments)) {
802 $_REQUEST['attachments'] = $attachments;
805 // set this so that the item_post() function is quiet and doesn't redirect or emit json
807 $_REQUEST['api_source'] = true;
809 if (empty($_REQUEST['source'])) {
810 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
813 // call out normal post function
814 $item_id = item_post($a);
816 if (!empty($ressources) && !empty($item_id)) {
817 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
818 foreach ($ressources as $ressource) {
819 Photo::setPermissionForRessource($ressource, $uid, $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
823 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
825 // output the post that we just posted.
826 $status_info = DI::twitterStatus()->createFromItemId($item_id, $uid, $include_entities)->toArray();
827 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
830 api_register_func('api/statuses/update', 'api_statuses_update', true);
831 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true);
832 api_register_func('api/statuses/mediap', 'api_statuses_update', true);
837 * @param string $type Return type (atom, rss, xml, json)
839 * @return array|string
840 * @throws BadRequestException
841 * @throws ForbiddenException
842 * @throws ImagickException
843 * @throws InternalServerErrorException
844 * @throws UnauthorizedException
845 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
847 function api_statuses_repeat($type)
849 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
850 $uid = BaseApi::getCurrentUserID();
853 $id = intval(DI::args()->getArgv()[3] ?? 0);
856 $id = intval($_REQUEST['id'] ?? 0);
861 $id = intval(DI::args()->getArgv()[4] ?? 0);
864 logger::notice('API: api_statuses_repeat: ' . $id);
866 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
867 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
869 if (DBA::isResult($item) && !empty($item['body'])) {
870 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
871 if (!Item::performActivity($id, 'announce', $uid)) {
872 throw new InternalServerErrorException();
877 if (strpos($item['body'], "[/share]") !== false) {
878 $pos = strpos($item['body'], "[share");
879 $post = substr($item['body'], $pos);
881 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
883 if (!empty($item['title'])) {
884 $post .= '[h3]' . $item['title'] . "[/h3]\n";
887 $post .= $item['body'];
890 $_REQUEST['body'] = $post;
891 $_REQUEST['profile_uid'] = $uid;
892 $_REQUEST['api_source'] = true;
894 if (empty($_REQUEST['source'])) {
895 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
898 $item_id = item_post(DI::app());
901 throw new ForbiddenException();
904 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
906 // output the post that we just posted.
907 $status_info = DI::twitterStatus()->createFromItemId($item_id, $uid, $include_entities)->toArray();
908 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
911 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true);
914 * Returns all lists the user subscribes to.
916 * @param string $type Return type (atom, rss, xml, json)
918 * @return array|string
919 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
921 function api_lists_list($type)
923 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
925 /// @TODO $ret is not filled here?
926 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
929 api_register_func('api/lists/list', 'api_lists_list', true);
930 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
933 * Returns all groups the user owns.
935 * @param string $type Return type (atom, rss, xml, json)
937 * @return array|string
938 * @throws BadRequestException
939 * @throws ForbiddenException
940 * @throws ImagickException
941 * @throws InternalServerErrorException
942 * @throws UnauthorizedException
943 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
945 function api_lists_ownerships($type)
947 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
948 $uid = BaseApi::getCurrentUserID();
951 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
953 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
955 // loop through all groups
957 foreach ($groups as $group) {
958 if ($group['visible']) {
964 'name' => $group['name'],
965 'id' => intval($group['id']),
966 'id_str' => (string) $group['id'],
967 'user' => $user_info,
971 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
974 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
977 * Sends a new direct message.
979 * @param string $type Return type (atom, rss, xml, json)
981 * @return array|string
982 * @throws BadRequestException
983 * @throws ForbiddenException
984 * @throws ImagickException
985 * @throws InternalServerErrorException
986 * @throws NotFoundException
987 * @throws UnauthorizedException
988 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
990 function api_direct_messages_new($type)
992 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
993 $uid = BaseApi::getCurrentUserID();
995 if (empty($_POST["text"]) || empty($_REQUEST['screen_name']) && empty($_REQUEST['user_id'])) {
999 $sender = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1001 $cid = BaseApi::getContactIDForSearchterm($_REQUEST['screen_name'] ?? '', $_REQUEST['profileurl'] ?? '', $_REQUEST['user_id'] ?? 0, 0);
1003 throw new NotFoundException('Recipient not found');
1007 if (!empty($_REQUEST['replyto'])) {
1008 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
1009 $replyto = $mail['parent-uri'];
1010 $sub = $mail['title'];
1012 if (!empty($_REQUEST['title'])) {
1013 $sub = $_REQUEST['title'];
1015 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
1019 $cdata = Contact::getPublicAndUserContactID($cid, $uid);
1021 $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
1024 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
1025 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid, true)->toArray(), $sender);
1027 $ret = ["error" => $id];
1030 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
1033 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true);
1036 * delete a direct_message from mail table through api
1038 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1039 * @return string|array
1040 * @throws BadRequestException
1041 * @throws ForbiddenException
1042 * @throws ImagickException
1043 * @throws InternalServerErrorException
1044 * @throws UnauthorizedException
1045 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
1047 function api_direct_messages_destroy($type)
1049 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1050 $uid = BaseApi::getCurrentUserID();
1053 $id = $_REQUEST['id'] ?? 0;
1055 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
1056 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
1057 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
1059 // error if no id or parenturi specified (for clients posting parent-uri as well)
1060 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
1061 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
1062 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
1065 // BadRequestException if no id specified (for clients using Twitter API)
1067 throw new BadRequestException('Message id not specified');
1070 // add parent-uri to sql command if specified by calling app
1071 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
1073 // error message if specified id is not in database
1074 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
1075 if ($verbose == "true") {
1076 $answer = ['result' => 'error', 'message' => 'message id not in database'];
1077 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
1079 /// @todo BadRequestException ok for Twitter API clients?
1080 throw new BadRequestException('message id not in database');
1084 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
1086 if ($verbose == "true") {
1089 $answer = ['result' => 'ok', 'message' => 'message deleted'];
1090 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
1092 $answer = ['result' => 'error', 'message' => 'unknown error'];
1093 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
1096 /// @todo return JSON data like Twitter API not yet implemented
1099 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true);
1103 * @param string $type Return type (atom, rss, xml, json)
1104 * @param string $box
1105 * @param string $verbose
1107 * @return array|string
1108 * @throws BadRequestException
1109 * @throws ForbiddenException
1110 * @throws ImagickException
1111 * @throws InternalServerErrorException
1112 * @throws UnauthorizedException
1114 function api_direct_messages_box($type, $box, $verbose)
1116 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1117 $uid = BaseApi::getCurrentUserID();
1120 $count = $_GET['count'] ?? 20;
1121 $page = $_REQUEST['page'] ?? 1;
1123 $since_id = $_REQUEST['since_id'] ?? 0;
1124 $max_id = $_REQUEST['max_id'] ?? 0;
1126 $user_id = $_REQUEST['user_id'] ?? '';
1127 $screen_name = $_REQUEST['screen_name'] ?? '';
1129 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1131 $profile_url = $user_info["url"];
1134 $start = max(0, ($page - 1) * $count);
1139 if ($box=="sentbox") {
1140 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
1141 } elseif ($box == "conversation") {
1142 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
1143 } elseif ($box == "all") {
1144 $sql_extra = "true";
1145 } elseif ($box == "inbox") {
1146 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
1150 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
1153 if ($user_id != "") {
1154 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
1155 } elseif ($screen_name !="") {
1156 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
1159 $r = DBA::toArray(DBA::p(
1160 "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 ?,?",
1166 if ($verbose == "true" && !DBA::isResult($r)) {
1167 $answer = ['result' => 'error', 'message' => 'no mails available'];
1168 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
1172 foreach ($r as $item) {
1173 if ($box == "inbox" || $item['from-url'] != $profile_url) {
1174 $recipient = $user_info;
1175 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1176 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
1177 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1178 $sender = $user_info;
1181 if (isset($recipient) && isset($sender)) {
1182 $ret[] = api_format_messages($item, $recipient, $sender);
1186 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
1190 * Returns the most recent direct messages sent by the user.
1192 * @param string $type Return type (atom, rss, xml, json)
1194 * @return array|string
1195 * @throws BadRequestException
1196 * @throws ForbiddenException
1197 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
1199 function api_direct_messages_sentbox($type)
1201 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1202 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
1203 return api_direct_messages_box($type, "sentbox", $verbose);
1206 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
1209 * Returns the most recent direct messages sent to the user.
1211 * @param string $type Return type (atom, rss, xml, json)
1213 * @return array|string
1214 * @throws BadRequestException
1215 * @throws ForbiddenException
1216 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
1218 function api_direct_messages_inbox($type)
1220 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1221 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
1222 return api_direct_messages_box($type, "inbox", $verbose);
1225 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
1229 * @param string $type Return type (atom, rss, xml, json)
1231 * @return array|string
1232 * @throws BadRequestException
1233 * @throws ForbiddenException
1235 function api_direct_messages_all($type)
1237 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1238 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
1239 return api_direct_messages_box($type, "all", $verbose);
1242 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
1246 * @param string $type Return type (atom, rss, xml, json)
1248 * @return array|string
1249 * @throws BadRequestException
1250 * @throws ForbiddenException
1252 function api_direct_messages_conversation($type)
1254 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1255 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
1256 return api_direct_messages_box($type, "conversation", $verbose);
1259 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
1262 * list all photos of the authenticated user
1264 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1265 * @return string|array
1266 * @throws ForbiddenException
1267 * @throws InternalServerErrorException
1269 function api_fr_photos_list($type)
1271 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1272 $uid = BaseApi::getCurrentUserID();
1274 $r = DBA::toArray(DBA::p(
1275 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
1276 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
1277 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
1278 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
1281 'image/jpeg' => 'jpg',
1282 'image/png' => 'png',
1283 'image/gif' => 'gif'
1285 $data = ['photo'=>[]];
1286 if (DBA::isResult($r)) {
1287 foreach ($r as $rr) {
1289 $photo['id'] = $rr['resource-id'];
1290 $photo['album'] = $rr['album'];
1291 $photo['filename'] = $rr['filename'];
1292 $photo['type'] = $rr['type'];
1293 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
1294 $photo['created'] = $rr['created'];
1295 $photo['edited'] = $rr['edited'];
1296 $photo['desc'] = $rr['desc'];
1298 if ($type == "xml") {
1299 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
1301 $photo['thumb'] = $thumb;
1302 $data['photo'][] = $photo;
1306 return DI::apiResponse()->formatData("photos", $type, $data);
1309 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
1312 * upload a new photo or change an existing photo
1314 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1315 * @return string|array
1316 * @throws BadRequestException
1317 * @throws ForbiddenException
1318 * @throws ImagickException
1319 * @throws InternalServerErrorException
1320 * @throws NotFoundException
1322 function api_fr_photo_create_update($type)
1324 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1325 $uid = BaseApi::getCurrentUserID();
1328 $photo_id = $_REQUEST['photo_id'] ?? null;
1329 $desc = $_REQUEST['desc'] ?? null;
1330 $album = $_REQUEST['album'] ?? null;
1331 $album_new = $_REQUEST['album_new'] ?? null;
1332 $allow_cid = $_REQUEST['allow_cid'] ?? null;
1333 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
1334 $allow_gid = $_REQUEST['allow_gid'] ?? null;
1335 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
1336 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
1338 // do several checks on input parameters
1339 // we do not allow calls without album string
1340 if ($album == null) {
1341 throw new BadRequestException("no albumname specified");
1343 // if photo_id == null --> we are uploading a new photo
1344 if ($photo_id == null) {
1347 // error if no media posted in create-mode
1348 if (empty($_FILES['media'])) {
1350 throw new BadRequestException("no media data submitted");
1353 // album_new will be ignored in create-mode
1358 // check if photo is existing in databasei
1359 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
1360 throw new BadRequestException("photo not available");
1364 // checks on acl strings provided by clients
1365 $acl_input_error = false;
1366 $acl_input_error |= check_acl_input($allow_cid, $uid);
1367 $acl_input_error |= check_acl_input($deny_cid, $uid);
1368 $acl_input_error |= check_acl_input($allow_gid, $uid);
1369 $acl_input_error |= check_acl_input($deny_gid, $uid);
1370 if ($acl_input_error) {
1371 throw new BadRequestException("acl data invalid");
1373 // now let's upload the new media in create-mode
1374 if ($mode == "create") {
1375 $media = $_FILES['media'];
1376 $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);
1378 // return success of updating or error message
1379 if (!is_null($data)) {
1380 return DI::apiResponse()->formatData("photo_create", $type, $data);
1382 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
1386 // now let's do the changes in update-mode
1387 if ($mode == "update") {
1388 $updated_fields = [];
1390 if (!is_null($desc)) {
1391 $updated_fields['desc'] = $desc;
1394 if (!is_null($album_new)) {
1395 $updated_fields['album'] = $album_new;
1398 if (!is_null($allow_cid)) {
1399 $allow_cid = trim($allow_cid);
1400 $updated_fields['allow_cid'] = $allow_cid;
1403 if (!is_null($deny_cid)) {
1404 $deny_cid = trim($deny_cid);
1405 $updated_fields['deny_cid'] = $deny_cid;
1408 if (!is_null($allow_gid)) {
1409 $allow_gid = trim($allow_gid);
1410 $updated_fields['allow_gid'] = $allow_gid;
1413 if (!is_null($deny_gid)) {
1414 $deny_gid = trim($deny_gid);
1415 $updated_fields['deny_gid'] = $deny_gid;
1419 if (count($updated_fields) > 0) {
1420 $nothingtodo = false;
1421 $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
1423 $nothingtodo = true;
1426 if (!empty($_FILES['media'])) {
1427 $nothingtodo = false;
1428 $media = $_FILES['media'];
1429 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
1430 if (!is_null($data)) {
1431 return DI::apiResponse()->formatData("photo_update", $type, $data);
1435 // return success of updating or error message
1437 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
1438 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1441 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
1442 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1444 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
1447 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
1450 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true);
1451 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true);
1454 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
1456 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1457 * @return string|array
1458 * @throws BadRequestException
1459 * @throws ForbiddenException
1460 * @throws InternalServerErrorException
1461 * @throws NotFoundException
1463 function api_fr_photo_detail($type)
1465 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1466 $uid = BaseApi::getCurrentUserID();
1468 if (empty($_REQUEST['photo_id'])) {
1469 throw new BadRequestException("No photo id.");
1472 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
1473 $photo_id = $_REQUEST['photo_id'];
1475 // prepare json/xml output with data from database for the requested photo
1476 $data = prepare_photo_data($type, $scale, $photo_id, $uid);
1478 return DI::apiResponse()->formatData("photo_detail", $type, $data);
1481 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
1484 * updates the profile image for the user (either a specified profile or the default profile)
1486 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1488 * @return string|array
1489 * @throws BadRequestException
1490 * @throws ForbiddenException
1491 * @throws ImagickException
1492 * @throws InternalServerErrorException
1493 * @throws NotFoundException
1494 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
1496 function api_account_update_profile_image($type)
1498 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1499 $uid = BaseApi::getCurrentUserID();
1502 $profile_id = $_REQUEST['profile_id'] ?? 0;
1504 // error if image data is missing
1505 if (empty($_FILES['image'])) {
1506 throw new BadRequestException("no media data submitted");
1509 // check if specified profile id is valid
1510 if ($profile_id != 0) {
1511 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
1512 // error message if specified profile id is not in database
1513 if (!DBA::isResult($profile)) {
1514 throw new BadRequestException("profile_id not available");
1516 $is_default_profile = $profile['is-default'];
1518 $is_default_profile = 1;
1521 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
1523 if (!empty($_FILES['image'])) {
1524 $media = $_FILES['image'];
1525 } elseif (!empty($_FILES['media'])) {
1526 $media = $_FILES['media'];
1528 // save new profile image
1529 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
1532 if (is_array($media['type'])) {
1533 $filetype = $media['type'][0];
1535 $filetype = $media['type'];
1537 if ($filetype == "image/jpeg") {
1539 } elseif ($filetype == "image/png") {
1542 throw new InternalServerErrorException('Unsupported filetype');
1545 // change specified profile or all profiles to the new resource-id
1546 if ($is_default_profile) {
1547 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
1548 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
1550 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
1551 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
1552 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
1555 Contact::updateSelfFromUserID($uid, true);
1557 // Update global directory in background
1558 Profile::publishUpdate($uid);
1560 // output for client
1562 $skip_status = $_REQUEST['skip_status'] ?? false;
1564 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
1566 // "verified" isn't used here in the standard
1567 unset($user_info["verified"]);
1569 // "uid" is only needed for some internal stuff, so remove it from here
1570 unset($user_info['uid']);
1572 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
1574 // SaveMediaToDatabase failed for some reason
1575 throw new InternalServerErrorException("image upload failed");
1579 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true);
1582 * Return all or a specified group of the user with the containing contacts.
1584 * @param string $type Return type (atom, rss, xml, json)
1586 * @return array|string
1587 * @throws BadRequestException
1588 * @throws ForbiddenException
1589 * @throws ImagickException
1590 * @throws InternalServerErrorException
1591 * @throws UnauthorizedException
1593 function api_friendica_group_show($type)
1595 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1596 $uid = BaseApi::getCurrentUserID();
1599 $gid = $_REQUEST['gid'] ?? 0;
1601 // get data of the specified group id or all groups if not specified
1603 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
1605 // error message if specified gid is not in database
1606 if (!DBA::isResult($groups)) {
1607 throw new BadRequestException("gid not available");
1610 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
1613 // loop through all groups and retrieve all members for adding data in the user array
1615 foreach ($groups as $rr) {
1616 $members = Contact\Group::getById($rr['id']);
1619 if ($type == "xml") {
1620 $user_element = "users";
1622 foreach ($members as $member) {
1623 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
1624 $users[$k++.":user"] = $user;
1627 $user_element = "user";
1628 foreach ($members as $member) {
1629 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
1633 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
1635 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
1638 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
1643 * @param string $type Return type (atom, rss, xml, json)
1645 * @return array|string
1646 * @throws BadRequestException
1647 * @throws ForbiddenException
1648 * @throws ImagickException
1649 * @throws InternalServerErrorException
1650 * @throws UnauthorizedException
1651 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
1653 function api_lists_destroy($type)
1655 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1656 $uid = BaseApi::getCurrentUserID();
1659 $gid = $_REQUEST['list_id'] ?? 0;
1661 // error if no gid specified
1663 throw new BadRequestException('gid not specified');
1666 // get data of the specified group id
1667 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1668 // error message if specified gid is not in database
1670 throw new BadRequestException('gid not available');
1673 if (Group::remove($gid)) {
1675 'name' => $group['name'],
1676 'id' => intval($gid),
1677 'id_str' => (string) $gid,
1678 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1681 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1685 api_register_func('api/lists/destroy', 'api_lists_destroy', true);
1688 * Create the specified group with the posted array of contacts.
1690 * @param string $type Return type (atom, rss, xml, json)
1692 * @return array|string
1693 * @throws BadRequestException
1694 * @throws ForbiddenException
1695 * @throws ImagickException
1696 * @throws InternalServerErrorException
1697 * @throws UnauthorizedException
1699 function api_friendica_group_create($type)
1701 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1702 $uid = BaseApi::getCurrentUserID();
1705 $name = $_REQUEST['name'] ?? '';
1706 $json = json_decode($_POST['json'], true);
1707 $users = $json['user'];
1709 $success = group_create($name, $uid, $users);
1711 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
1714 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true);
1717 * Create a new group.
1719 * @param string $type Return type (atom, rss, xml, json)
1721 * @return array|string
1722 * @throws BadRequestException
1723 * @throws ForbiddenException
1724 * @throws ImagickException
1725 * @throws InternalServerErrorException
1726 * @throws UnauthorizedException
1727 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
1729 function api_lists_create($type)
1731 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1732 $uid = BaseApi::getCurrentUserID();
1735 $name = $_REQUEST['name'] ?? '';
1737 $success = group_create($name, $uid);
1738 if ($success['success']) {
1740 'name' => $success['name'],
1741 'id' => intval($success['gid']),
1742 'id_str' => (string) $success['gid'],
1743 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1746 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
1750 api_register_func('api/lists/create', 'api_lists_create', true);
1753 * Update information about a group.
1755 * @param string $type Return type (atom, rss, xml, json)
1757 * @return array|string
1758 * @throws BadRequestException
1759 * @throws ForbiddenException
1760 * @throws ImagickException
1761 * @throws InternalServerErrorException
1762 * @throws UnauthorizedException
1763 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
1765 function api_lists_update($type)
1767 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1768 $uid = BaseApi::getCurrentUserID();
1771 $gid = $_REQUEST['list_id'] ?? 0;
1772 $name = $_REQUEST['name'] ?? '';
1774 // error if no gid specified
1776 throw new BadRequestException('gid not specified');
1779 // get data of the specified group id
1780 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1781 // error message if specified gid is not in database
1783 throw new BadRequestException('gid not available');
1786 if (Group::update($gid, $name)) {
1789 'id' => intval($gid),
1790 'id_str' => (string) $gid,
1791 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1794 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1798 api_register_func('api/lists/update', 'api_lists_update', true);
1801 * search for direct_messages containing a searchstring through api
1803 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1804 * @param string $box
1805 * @return string|array (success: success=true if found and search_result contains found messages,
1806 * success=false if nothing was found, search_result='nothing found',
1807 * error: result=error with error message)
1808 * @throws BadRequestException
1809 * @throws ForbiddenException
1810 * @throws ImagickException
1811 * @throws InternalServerErrorException
1812 * @throws UnauthorizedException
1814 function api_friendica_direct_messages_search($type, $box = "")
1816 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1817 $uid = BaseApi::getCurrentUserID();
1820 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1821 $searchstring = $_REQUEST['searchstring'] ?? '';
1823 // error if no searchstring specified
1824 if ($searchstring == "") {
1825 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
1826 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
1829 // get data for the specified searchstring
1830 $r = DBA::toArray(DBA::p(
1831 "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",
1833 '%'.$searchstring.'%'
1836 $profile_url = $user_info["url"];
1838 // message if nothing was found
1839 if (!DBA::isResult($r)) {
1840 $success = ['success' => false, 'search_results' => 'problem with query'];
1841 } elseif (count($r) == 0) {
1842 $success = ['success' => false, 'search_results' => 'nothing found'];
1845 foreach ($r as $item) {
1846 if ($box == "inbox" || $item['from-url'] != $profile_url) {
1847 $recipient = $user_info;
1848 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1849 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
1850 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1851 $sender = $user_info;
1854 if (isset($recipient) && isset($sender)) {
1855 $ret[] = api_format_messages($item, $recipient, $sender);
1858 $success = ['success' => true, 'search_results' => $ret];
1861 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
1864 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);