3 * @copyright Copyright (C) 2010-2022, 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\Core\Logger;
28 use Friendica\Core\System;
29 use Friendica\Database\DBA;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Group;
33 use Friendica\Model\Item;
34 use Friendica\Model\Photo;
35 use Friendica\Model\Post;
36 use Friendica\Model\Profile;
37 use Friendica\Module\BaseApi;
38 use Friendica\Network\HTTPException;
39 use Friendica\Network\HTTPException\BadRequestException;
40 use Friendica\Network\HTTPException\ForbiddenException;
41 use Friendica\Network\HTTPException\InternalServerErrorException;
42 use Friendica\Network\HTTPException\NotFoundException;
43 use Friendica\Network\HTTPException\UnauthorizedException;
44 use Friendica\Object\Image;
45 use Friendica\Util\Images;
46 use Friendica\Util\Strings;
51 * Register a function to be the endpoint for defined API path.
53 * @param string $path API URL path, relative to DI::baseUrl()
54 * @param string $func Function name to call on path request
56 function api_register_func($path, $func)
64 // Workaround for hotot
65 $path = str_replace("api/", "api/1.1/", $path);
73 * Main API entry point
75 * Authenticate user, call registered API function, set HTTP headers
77 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
78 * @return string|array API call result
81 function api_call($command, $extension)
85 Logger::info('Legacy API call', ['command' => $command, 'extension' => $extension]);
88 foreach ($API as $p => $info) {
89 if (strpos($command, $p) === 0) {
90 Logger::debug(BaseApi::LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
92 $stamp = microtime(true);
93 $return = call_user_func($info['func'], $extension);
94 $duration = floatval(microtime(true) - $stamp);
96 Logger::info(BaseApi::LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
98 DI::profiler()->saveLog(DI::logger(), BaseApi::LOG_PREFIX . 'performance');
100 if (false === $return) {
102 * api function returned false withour throw an
103 * exception. This should not happend, throw a 500
105 throw new InternalServerErrorException();
108 switch ($extension) {
110 header("Content-Type: text/xml");
113 header("Content-Type: application/json");
114 if (!empty($return)) {
115 $json = json_encode(end($return));
116 if (!empty($_GET['callback'])) {
117 $json = $_GET['callback'] . "(" . $json . ")";
123 header("Content-Type: application/rss+xml");
124 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
127 header("Content-Type: application/atom+xml");
128 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
135 Logger::warning(BaseApi::LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
136 throw new NotFoundException();
137 } catch (HTTPException $e) {
138 Logger::notice(BaseApi::LOG_PREFIX . 'got exception', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString(), 'error' => $e]);
139 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $extension);
145 * @param string $acl_string
150 function check_acl_input($acl_string, $uid)
152 if (empty($acl_string)) {
156 $contact_not_found = false;
158 // split <x><y><z> into array of cid's
159 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
161 // check for each cid if it is available on server
162 $cid_array = $array[0];
163 foreach ($cid_array as $cid) {
164 $cid = str_replace("<", "", $cid);
165 $cid = str_replace(">", "", $cid);
166 $condition = ['id' => $cid, 'uid' => $uid];
167 $contact_not_found |= !DBA::exists('contact', $condition);
169 return $contact_not_found;
173 * @param string $mediatype
174 * @param array $media
175 * @param string $type
176 * @param string $album
177 * @param string $allow_cid
178 * @param string $deny_cid
179 * @param string $allow_gid
180 * @param string $deny_gid
181 * @param string $desc
182 * @param integer $phototype
183 * @param boolean $visibility
184 * @param string $photo_id
187 * @throws BadRequestException
188 * @throws ForbiddenException
189 * @throws ImagickException
190 * @throws InternalServerErrorException
191 * @throws NotFoundException
192 * @throws UnauthorizedException
194 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype, $visibility, $photo_id, $uid)
202 if (is_array($media)) {
203 if (is_array($media['tmp_name'])) {
204 $src = $media['tmp_name'][0];
206 $src = $media['tmp_name'];
208 if (is_array($media['name'])) {
209 $filename = basename($media['name'][0]);
211 $filename = basename($media['name']);
213 if (is_array($media['size'])) {
214 $filesize = intval($media['size'][0]);
216 $filesize = intval($media['size']);
218 if (is_array($media['type'])) {
219 $filetype = $media['type'][0];
221 $filetype = $media['type'];
225 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
228 "File upload src: " . $src . " - filename: " . $filename .
229 " - size: " . $filesize . " - type: " . $filetype);
231 // check if there was a php upload error
232 if ($filesize == 0 && $media['error'] == 1) {
233 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
235 // check against max upload size within Friendica instance
236 $maximagesize = DI::config()->get('system', 'maximagesize');
237 if ($maximagesize && ($filesize > $maximagesize)) {
238 $formattedBytes = Strings::formatBytes($maximagesize);
239 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
242 // create Photo instance with the data of the image
243 $imagedata = @file_get_contents($src);
244 $Image = new Image($imagedata, $filetype);
245 if (!$Image->isValid()) {
246 throw new InternalServerErrorException("unable to process image data");
249 // check orientation of image
250 $Image->orient($src);
253 // check max length of images on server
254 $max_length = DI::config()->get('system', 'max_image_length');
255 if ($max_length > 0) {
256 $Image->scaleDown($max_length);
257 logger::info("File upload: Scaling picture to new size " . $max_length);
259 $width = $Image->getWidth();
260 $height = $Image->getHeight();
262 // create a new resource-id if not already provided
263 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
265 if ($mediatype == "photo") {
266 // upload normal image (scales 0, 1, 2)
267 logger::info("photo upload: starting new photo upload");
269 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
271 logger::notice("photo upload: image upload with scale 0 (original size) failed");
273 if ($width > 640 || $height > 640) {
274 $Image->scaleDown(640);
275 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
277 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
281 if ($width > 320 || $height > 320) {
282 $Image->scaleDown(320);
283 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
285 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
288 logger::info("photo upload: new photo upload ended");
289 } elseif ($mediatype == "profileimage") {
290 // upload profile image (scales 4, 5, 6)
291 logger::info("photo upload: starting new profile image upload");
293 if ($width > 300 || $height > 300) {
294 $Image->scaleDown(300);
295 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
297 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
301 if ($width > 80 || $height > 80) {
302 $Image->scaleDown(80);
303 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
305 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
309 if ($width > 48 || $height > 48) {
310 $Image->scaleDown(48);
311 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
313 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
316 $Image->__destruct();
317 logger::info("photo upload: new profile image upload ended");
321 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
322 if ($photo_id == null && $mediatype == "photo") {
323 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid);
325 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
326 return prepare_photo_data($type, false, $resource_id, $uid);
328 throw new InternalServerErrorException("image upload failed");
329 DI::page()->exit(DI::apiResponse());
335 * @param string $hash
336 * @param string $allow_cid
337 * @param string $deny_cid
338 * @param string $allow_gid
339 * @param string $deny_gid
340 * @param string $filetype
341 * @param boolean $visibility
343 * @throws InternalServerErrorException
345 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid)
347 // get data about the api authenticated user
348 $uri = Item::newURI(intval($uid));
349 $owner_record = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
352 $arr['guid'] = System::createUUID();
355 $arr['post-type'] = Item::PT_IMAGE;
357 $arr['resource-id'] = $hash;
358 $arr['contact-id'] = $owner_record['id'];
359 $arr['owner-name'] = $owner_record['name'];
360 $arr['owner-link'] = $owner_record['url'];
361 $arr['owner-avatar'] = $owner_record['thumb'];
362 $arr['author-name'] = $owner_record['name'];
363 $arr['author-link'] = $owner_record['url'];
364 $arr['author-avatar'] = $owner_record['thumb'];
366 $arr['allow_cid'] = $allow_cid;
367 $arr['allow_gid'] = $allow_gid;
368 $arr['deny_cid'] = $deny_cid;
369 $arr['deny_gid'] = $deny_gid;
370 $arr['visible'] = $visibility;
373 $typetoext = Images::supportedTypes();
375 // adds link to the thumbnail scale photo
376 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
377 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
380 // do the magic for storing the item in the database and trigger the federation to other contacts
386 * @param string $type
388 * @param string $photo_id
391 * @throws BadRequestException
392 * @throws ForbiddenException
393 * @throws ImagickException
394 * @throws InternalServerErrorException
395 * @throws NotFoundException
396 * @throws UnauthorizedException
398 function prepare_photo_data($type, $scale, $photo_id, $uid)
400 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
401 $data_sql = ($scale === false ? "" : "data, ");
403 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
404 // clients needs to convert this in their way for further processing
405 $r = DBA::toArray(DBA::p(
406 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
407 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
408 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
409 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
410 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
411 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
417 'image/jpeg' => 'jpg',
418 'image/png' => 'png',
422 // prepare output data for photo
423 if (DBA::isResult($r)) {
424 $data = ['photo' => $r[0]];
425 $data['photo']['id'] = $data['photo']['resource-id'];
426 if ($scale !== false) {
427 $data['photo']['data'] = base64_encode($data['photo']['data']);
429 unset($data['photo']['datasize']); //needed only with scale param
431 if ($type == "xml") {
432 $data['photo']['links'] = [];
433 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
434 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
436 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
439 $data['photo']['link'] = [];
440 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
442 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
443 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
447 unset($data['photo']['resource-id']);
448 unset($data['photo']['minscale']);
449 unset($data['photo']['maxscale']);
451 throw new NotFoundException();
454 // retrieve item element for getting activities (like, dislike etc.) related to photo
455 $condition = ['uid' => $uid, 'resource-id' => $photo_id];
456 $item = Post::selectFirst(['id', 'uid', 'uri', 'uri-id', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
457 if (!DBA::isResult($item)) {
458 throw new NotFoundException('Photo-related item not found.');
461 $data['photo']['friendica_activities'] = DI::friendicaActivities()->createFromUriId($item['uri-id'], $item['uid'], $type);
463 // retrieve comments on photo
464 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
465 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
467 $statuses = Post::selectForUser($uid, [], $condition);
469 // prepare output of comments
471 while ($status = DBA::fetch($statuses)) {
472 $commentData[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'])->toArray();
474 DBA::close($statuses);
477 if ($type == "xml") {
479 foreach ($commentData as $comment) {
480 $comments[$k++ . ":comment"] = $comment;
483 foreach ($commentData as $comment) {
484 $comments[] = $comment;
487 $data['photo']['friendica_comments'] = $comments;
489 // include info if rights on photo and rights on item are mismatching
490 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
491 $data['photo']['deny_cid'] != $item['deny_cid'] ||
492 $data['photo']['allow_gid'] != $item['allow_gid'] ||
493 $data['photo']['deny_gid'] != $item['deny_gid'];
494 $data['photo']['rights_mismatch'] = $rights_mismatch;
500 * Add a new group to the database.
502 * @param string $name Group name
503 * @param int $uid User ID
504 * @param array $users List of users to add to the group
507 * @throws BadRequestException
509 function group_create($name, $uid, $users = [])
511 // error if no name specified
513 throw new BadRequestException('group name not specified');
516 // error message if specified group name already exists
517 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
518 throw new BadRequestException('group name already exists');
521 // Check if the group needs to be reactivated
522 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
523 $reactivate_group = true;
527 $ret = Group::create($uid, $name);
529 $gid = Group::getIdByName($uid, $name);
531 throw new BadRequestException('other API error');
535 $erroraddinguser = false;
537 foreach ($users as $user) {
539 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
540 Group::addMember($gid, $cid);
542 $erroraddinguser = true;
543 $errorusers[] = $cid;
547 // return success message incl. missing users in array
548 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
550 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
558 * Returns all lists the user subscribes to.
560 * @param string $type Return type (atom, rss, xml, json)
562 * @return array|string
563 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
565 function api_lists_list($type)
567 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
569 /// @TODO $ret is not filled here?
570 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
573 api_register_func('api/lists/list', 'api_lists_list', true);
574 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
577 * Returns all groups the user owns.
579 * @param string $type Return type (atom, rss, xml, json)
581 * @return array|string
582 * @throws BadRequestException
583 * @throws ForbiddenException
584 * @throws ImagickException
585 * @throws InternalServerErrorException
586 * @throws UnauthorizedException
587 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
589 function api_lists_ownerships($type)
591 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
592 $uid = BaseApi::getCurrentUserID();
595 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
597 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
599 // loop through all groups
601 foreach ($groups as $group) {
602 if ($group['visible']) {
608 'name' => $group['name'],
609 'id' => intval($group['id']),
610 'id_str' => (string) $group['id'],
611 'user' => $user_info,
615 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
618 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
621 * list all photos of the authenticated user
623 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
624 * @return string|array
625 * @throws ForbiddenException
626 * @throws InternalServerErrorException
628 function api_fr_photos_list($type)
630 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
631 $uid = BaseApi::getCurrentUserID();
633 $r = DBA::toArray(DBA::p(
634 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
635 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
636 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
637 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
640 'image/jpeg' => 'jpg',
641 'image/png' => 'png',
644 $data = ['photo'=>[]];
645 if (DBA::isResult($r)) {
646 foreach ($r as $rr) {
648 $photo['id'] = $rr['resource-id'];
649 $photo['album'] = $rr['album'];
650 $photo['filename'] = $rr['filename'];
651 $photo['type'] = $rr['type'];
652 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
653 $photo['created'] = $rr['created'];
654 $photo['edited'] = $rr['edited'];
655 $photo['desc'] = $rr['desc'];
657 if ($type == "xml") {
658 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
660 $photo['thumb'] = $thumb;
661 $data['photo'][] = $photo;
665 return DI::apiResponse()->formatData("photos", $type, $data);
668 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
671 * upload a new photo or change an existing photo
673 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
674 * @return string|array
675 * @throws BadRequestException
676 * @throws ForbiddenException
677 * @throws ImagickException
678 * @throws InternalServerErrorException
679 * @throws NotFoundException
681 function api_fr_photo_create_update($type)
683 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
684 $uid = BaseApi::getCurrentUserID();
687 $photo_id = $_REQUEST['photo_id'] ?? null;
688 $desc = $_REQUEST['desc'] ?? null;
689 $album = $_REQUEST['album'] ?? null;
690 $album_new = $_REQUEST['album_new'] ?? null;
691 $allow_cid = $_REQUEST['allow_cid'] ?? null;
692 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
693 $allow_gid = $_REQUEST['allow_gid'] ?? null;
694 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
695 // Pictures uploaded via API never get posted as a visible status
696 // See https://github.com/friendica/friendica/issues/10990
699 // do several checks on input parameters
700 // we do not allow calls without album string
701 if ($album == null) {
702 throw new BadRequestException("no albumname specified");
704 // if photo_id == null --> we are uploading a new photo
705 if ($photo_id == null) {
708 // error if no media posted in create-mode
709 if (empty($_FILES['media'])) {
711 throw new BadRequestException("no media data submitted");
714 // album_new will be ignored in create-mode
719 // check if photo is existing in databasei
720 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
721 throw new BadRequestException("photo not available");
725 // checks on acl strings provided by clients
726 $acl_input_error = false;
727 $acl_input_error |= check_acl_input($allow_cid, $uid);
728 $acl_input_error |= check_acl_input($deny_cid, $uid);
729 $acl_input_error |= check_acl_input($allow_gid, $uid);
730 $acl_input_error |= check_acl_input($deny_gid, $uid);
731 if ($acl_input_error) {
732 throw new BadRequestException("acl data invalid");
734 // now let's upload the new media in create-mode
735 if ($mode == "create") {
736 $media = $_FILES['media'];
737 $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);
739 // return success of updating or error message
740 if (!is_null($data)) {
741 return DI::apiResponse()->formatData("photo_create", $type, $data);
743 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
747 // now let's do the changes in update-mode
748 if ($mode == "update") {
749 $updated_fields = [];
751 if (!is_null($desc)) {
752 $updated_fields['desc'] = $desc;
755 if (!is_null($album_new)) {
756 $updated_fields['album'] = $album_new;
759 if (!is_null($allow_cid)) {
760 $allow_cid = trim($allow_cid);
761 $updated_fields['allow_cid'] = $allow_cid;
764 if (!is_null($deny_cid)) {
765 $deny_cid = trim($deny_cid);
766 $updated_fields['deny_cid'] = $deny_cid;
769 if (!is_null($allow_gid)) {
770 $allow_gid = trim($allow_gid);
771 $updated_fields['allow_gid'] = $allow_gid;
774 if (!is_null($deny_gid)) {
775 $deny_gid = trim($deny_gid);
776 $updated_fields['deny_gid'] = $deny_gid;
780 if (count($updated_fields) > 0) {
781 $nothingtodo = false;
782 $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
787 if (!empty($_FILES['media'])) {
788 $nothingtodo = false;
789 $media = $_FILES['media'];
790 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
791 if (!is_null($data)) {
792 return DI::apiResponse()->formatData("photo_update", $type, $data);
796 // return success of updating or error message
798 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
799 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
802 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
803 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
805 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
808 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
811 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true);
812 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true);
815 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
817 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
818 * @return string|array
819 * @throws BadRequestException
820 * @throws ForbiddenException
821 * @throws InternalServerErrorException
822 * @throws NotFoundException
824 function api_fr_photo_detail($type)
826 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
827 $uid = BaseApi::getCurrentUserID();
829 if (empty($_REQUEST['photo_id'])) {
830 throw new BadRequestException("No photo id.");
833 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
834 $photo_id = $_REQUEST['photo_id'];
836 // prepare json/xml output with data from database for the requested photo
837 $data = prepare_photo_data($type, $scale, $photo_id, $uid);
839 return DI::apiResponse()->formatData("photo_detail", $type, $data);
842 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
845 * updates the profile image for the user (either a specified profile or the default profile)
847 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
849 * @return string|array
850 * @throws BadRequestException
851 * @throws ForbiddenException
852 * @throws ImagickException
853 * @throws InternalServerErrorException
854 * @throws NotFoundException
855 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
857 function api_account_update_profile_image($type)
859 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
860 $uid = BaseApi::getCurrentUserID();
863 $profile_id = $_REQUEST['profile_id'] ?? 0;
865 // error if image data is missing
866 if (empty($_FILES['image'])) {
867 throw new BadRequestException("no media data submitted");
870 // check if specified profile id is valid
871 if ($profile_id != 0) {
872 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
873 // error message if specified profile id is not in database
874 if (!DBA::isResult($profile)) {
875 throw new BadRequestException("profile_id not available");
877 $is_default_profile = $profile['is-default'];
879 $is_default_profile = 1;
882 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
884 if (!empty($_FILES['image'])) {
885 $media = $_FILES['image'];
886 } elseif (!empty($_FILES['media'])) {
887 $media = $_FILES['media'];
889 // save new profile image
890 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
893 if (is_array($media['type'])) {
894 $filetype = $media['type'][0];
896 $filetype = $media['type'];
898 if ($filetype == "image/jpeg") {
900 } elseif ($filetype == "image/png") {
903 throw new InternalServerErrorException('Unsupported filetype');
906 // change specified profile or all profiles to the new resource-id
907 if ($is_default_profile) {
908 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
909 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
911 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
912 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
913 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
916 Contact::updateSelfFromUserID($uid, true);
918 // Update global directory in background
919 Profile::publishUpdate($uid);
923 $skip_status = $_REQUEST['skip_status'] ?? false;
925 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
927 // "verified" isn't used here in the standard
928 unset($user_info["verified"]);
930 // "uid" is only needed for some internal stuff, so remove it from here
931 unset($user_info['uid']);
933 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
935 // SaveMediaToDatabase failed for some reason
936 throw new InternalServerErrorException("image upload failed");
940 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true);
943 * Return all or a specified group of the user with the containing contacts.
945 * @param string $type Return type (atom, rss, xml, json)
947 * @return array|string
948 * @throws BadRequestException
949 * @throws ForbiddenException
950 * @throws ImagickException
951 * @throws InternalServerErrorException
952 * @throws UnauthorizedException
954 function api_friendica_group_show($type)
956 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
957 $uid = BaseApi::getCurrentUserID();
960 $gid = $_REQUEST['gid'] ?? 0;
962 // get data of the specified group id or all groups if not specified
964 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
966 // error message if specified gid is not in database
967 if (!DBA::isResult($groups)) {
968 throw new BadRequestException("gid not available");
971 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
974 // loop through all groups and retrieve all members for adding data in the user array
976 foreach ($groups as $rr) {
977 $members = Contact\Group::getById($rr['id']);
980 if ($type == "xml") {
981 $user_element = "users";
983 foreach ($members as $member) {
984 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
985 $users[$k++.":user"] = $user;
988 $user_element = "user";
989 foreach ($members as $member) {
990 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
994 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
996 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
999 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
1004 * @param string $type Return type (atom, rss, xml, json)
1006 * @return array|string
1007 * @throws BadRequestException
1008 * @throws ForbiddenException
1009 * @throws ImagickException
1010 * @throws InternalServerErrorException
1011 * @throws UnauthorizedException
1012 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
1014 function api_lists_destroy($type)
1016 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1017 $uid = BaseApi::getCurrentUserID();
1020 $gid = $_REQUEST['list_id'] ?? 0;
1022 // error if no gid specified
1024 throw new BadRequestException('gid not specified');
1027 // get data of the specified group id
1028 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1029 // error message if specified gid is not in database
1031 throw new BadRequestException('gid not available');
1034 if (Group::remove($gid)) {
1036 'name' => $group['name'],
1037 'id' => intval($gid),
1038 'id_str' => (string) $gid,
1039 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1042 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1046 api_register_func('api/lists/destroy', 'api_lists_destroy', true);
1049 * Create the specified group with the posted array of contacts.
1051 * @param string $type Return type (atom, rss, xml, json)
1053 * @return array|string
1054 * @throws BadRequestException
1055 * @throws ForbiddenException
1056 * @throws ImagickException
1057 * @throws InternalServerErrorException
1058 * @throws UnauthorizedException
1060 function api_friendica_group_create($type)
1062 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1063 $uid = BaseApi::getCurrentUserID();
1066 $name = $_REQUEST['name'] ?? '';
1067 $json = json_decode($_POST['json'], true);
1068 $users = $json['user'];
1070 $success = group_create($name, $uid, $users);
1072 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
1075 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true);
1078 * Create a new group.
1080 * @param string $type Return type (atom, rss, xml, json)
1082 * @return array|string
1083 * @throws BadRequestException
1084 * @throws ForbiddenException
1085 * @throws ImagickException
1086 * @throws InternalServerErrorException
1087 * @throws UnauthorizedException
1088 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
1090 function api_lists_create($type)
1092 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1093 $uid = BaseApi::getCurrentUserID();
1096 $name = $_REQUEST['name'] ?? '';
1098 $success = group_create($name, $uid);
1099 if ($success['success']) {
1101 'name' => $success['name'],
1102 'id' => intval($success['gid']),
1103 'id_str' => (string) $success['gid'],
1104 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1107 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
1111 api_register_func('api/lists/create', 'api_lists_create', true);
1114 * Update information about a group.
1116 * @param string $type Return type (atom, rss, xml, json)
1118 * @return array|string
1119 * @throws BadRequestException
1120 * @throws ForbiddenException
1121 * @throws ImagickException
1122 * @throws InternalServerErrorException
1123 * @throws UnauthorizedException
1124 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
1126 function api_lists_update($type)
1128 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1129 $uid = BaseApi::getCurrentUserID();
1132 $gid = $_REQUEST['list_id'] ?? 0;
1133 $name = $_REQUEST['name'] ?? '';
1135 // error if no gid specified
1137 throw new BadRequestException('gid not specified');
1140 // get data of the specified group id
1141 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1142 // error message if specified gid is not in database
1144 throw new BadRequestException('gid not available');
1147 if (Group::update($gid, $name)) {
1150 'id' => intval($gid),
1151 'id_str' => (string) $gid,
1152 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1155 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1159 api_register_func('api/lists/update', 'api_lists_update', true);