3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Logger;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Group;
35 use Friendica\Model\Item;
36 use Friendica\Model\Mail;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Post;
39 use Friendica\Model\Profile;
40 use Friendica\Module\BaseApi;
41 use Friendica\Network\HTTPException;
42 use Friendica\Network\HTTPException\BadRequestException;
43 use Friendica\Network\HTTPException\ForbiddenException;
44 use Friendica\Network\HTTPException\InternalServerErrorException;
45 use Friendica\Network\HTTPException\NotFoundException;
46 use Friendica\Network\HTTPException\UnauthorizedException;
47 use Friendica\Object\Image;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Images;
50 use Friendica\Util\Strings;
55 * Register a function to be the endpoint for defined API path.
57 * @param string $path API URL path, relative to DI::baseUrl()
58 * @param string $func Function name to call on path request
60 function api_register_func($path, $func)
68 // Workaround for hotot
69 $path = str_replace("api/", "api/1.1/", $path);
77 * Main API entry point
79 * Authenticate user, call registered API function, set HTTP headers
81 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
82 * @return string|array API call result
85 function api_call($command, $extension)
89 Logger::info('Legacy API call', ['command' => $command, 'extension' => $extension]);
92 foreach ($API as $p => $info) {
93 if (strpos($command, $p) === 0) {
94 Logger::debug(BaseApi::LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
96 $stamp = microtime(true);
97 $return = call_user_func($info['func'], $extension);
98 $duration = floatval(microtime(true) - $stamp);
100 Logger::info(BaseApi::LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
102 DI::profiler()->saveLog(DI::logger(), BaseApi::LOG_PREFIX . 'performance');
104 if (false === $return) {
106 * api function returned false withour throw an
107 * exception. This should not happend, throw a 500
109 throw new InternalServerErrorException();
112 switch ($extension) {
114 header("Content-Type: text/xml");
117 header("Content-Type: application/json");
118 if (!empty($return)) {
119 $json = json_encode(end($return));
120 if (!empty($_GET['callback'])) {
121 $json = $_GET['callback'] . "(" . $json . ")";
127 header("Content-Type: application/rss+xml");
128 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
131 header("Content-Type: application/atom+xml");
132 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
139 Logger::warning(BaseApi::LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
140 throw new NotFoundException();
141 } catch (HTTPException $e) {
142 Logger::notice(BaseApi::LOG_PREFIX . 'got exception', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString(), 'error' => $e]);
143 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $extension);
149 * @param string $acl_string
154 function check_acl_input($acl_string, $uid)
156 if (empty($acl_string)) {
160 $contact_not_found = false;
162 // split <x><y><z> into array of cid's
163 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
165 // check for each cid if it is available on server
166 $cid_array = $array[0];
167 foreach ($cid_array as $cid) {
168 $cid = str_replace("<", "", $cid);
169 $cid = str_replace(">", "", $cid);
170 $condition = ['id' => $cid, 'uid' => $uid];
171 $contact_not_found |= !DBA::exists('contact', $condition);
173 return $contact_not_found;
177 * @param string $mediatype
178 * @param array $media
179 * @param string $type
180 * @param string $album
181 * @param string $allow_cid
182 * @param string $deny_cid
183 * @param string $allow_gid
184 * @param string $deny_gid
185 * @param string $desc
186 * @param integer $phototype
187 * @param boolean $visibility
188 * @param string $photo_id
191 * @throws BadRequestException
192 * @throws ForbiddenException
193 * @throws ImagickException
194 * @throws InternalServerErrorException
195 * @throws NotFoundException
196 * @throws UnauthorizedException
198 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype, $visibility, $photo_id, $uid)
206 if (is_array($media)) {
207 if (is_array($media['tmp_name'])) {
208 $src = $media['tmp_name'][0];
210 $src = $media['tmp_name'];
212 if (is_array($media['name'])) {
213 $filename = basename($media['name'][0]);
215 $filename = basename($media['name']);
217 if (is_array($media['size'])) {
218 $filesize = intval($media['size'][0]);
220 $filesize = intval($media['size']);
222 if (is_array($media['type'])) {
223 $filetype = $media['type'][0];
225 $filetype = $media['type'];
229 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
232 "File upload src: " . $src . " - filename: " . $filename .
233 " - size: " . $filesize . " - type: " . $filetype);
235 // check if there was a php upload error
236 if ($filesize == 0 && $media['error'] == 1) {
237 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
239 // check against max upload size within Friendica instance
240 $maximagesize = DI::config()->get('system', 'maximagesize');
241 if ($maximagesize && ($filesize > $maximagesize)) {
242 $formattedBytes = Strings::formatBytes($maximagesize);
243 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
246 // create Photo instance with the data of the image
247 $imagedata = @file_get_contents($src);
248 $Image = new Image($imagedata, $filetype);
249 if (!$Image->isValid()) {
250 throw new InternalServerErrorException("unable to process image data");
253 // check orientation of image
254 $Image->orient($src);
257 // check max length of images on server
258 $max_length = DI::config()->get('system', 'max_image_length');
259 if ($max_length > 0) {
260 $Image->scaleDown($max_length);
261 logger::info("File upload: Scaling picture to new size " . $max_length);
263 $width = $Image->getWidth();
264 $height = $Image->getHeight();
266 // create a new resource-id if not already provided
267 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
269 if ($mediatype == "photo") {
270 // upload normal image (scales 0, 1, 2)
271 logger::info("photo upload: starting new photo upload");
273 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
275 logger::notice("photo upload: image upload with scale 0 (original size) failed");
277 if ($width > 640 || $height > 640) {
278 $Image->scaleDown(640);
279 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
281 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
285 if ($width > 320 || $height > 320) {
286 $Image->scaleDown(320);
287 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
289 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
292 logger::info("photo upload: new photo upload ended");
293 } elseif ($mediatype == "profileimage") {
294 // upload profile image (scales 4, 5, 6)
295 logger::info("photo upload: starting new profile image upload");
297 if ($width > 300 || $height > 300) {
298 $Image->scaleDown(300);
299 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
301 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
305 if ($width > 80 || $height > 80) {
306 $Image->scaleDown(80);
307 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
309 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
313 if ($width > 48 || $height > 48) {
314 $Image->scaleDown(48);
315 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
317 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
320 $Image->__destruct();
321 logger::info("photo upload: new profile image upload ended");
325 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
326 if ($photo_id == null && $mediatype == "photo") {
327 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid);
329 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
330 return prepare_photo_data($type, false, $resource_id, $uid);
332 throw new InternalServerErrorException("image upload failed");
333 DI::page()->exit(DI::apiResponse());
339 * @param string $hash
340 * @param string $allow_cid
341 * @param string $deny_cid
342 * @param string $allow_gid
343 * @param string $deny_gid
344 * @param string $filetype
345 * @param boolean $visibility
347 * @throws InternalServerErrorException
349 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid)
351 // get data about the api authenticated user
352 $uri = Item::newURI(intval($uid));
353 $owner_record = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
356 $arr['guid'] = System::createUUID();
359 $arr['post-type'] = Item::PT_IMAGE;
361 $arr['resource-id'] = $hash;
362 $arr['contact-id'] = $owner_record['id'];
363 $arr['owner-name'] = $owner_record['name'];
364 $arr['owner-link'] = $owner_record['url'];
365 $arr['owner-avatar'] = $owner_record['thumb'];
366 $arr['author-name'] = $owner_record['name'];
367 $arr['author-link'] = $owner_record['url'];
368 $arr['author-avatar'] = $owner_record['thumb'];
370 $arr['allow_cid'] = $allow_cid;
371 $arr['allow_gid'] = $allow_gid;
372 $arr['deny_cid'] = $deny_cid;
373 $arr['deny_gid'] = $deny_gid;
374 $arr['visible'] = $visibility;
377 $typetoext = Images::supportedTypes();
379 // adds link to the thumbnail scale photo
380 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
381 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
384 // do the magic for storing the item in the database and trigger the federation to other contacts
390 * @param string $type
392 * @param string $photo_id
395 * @throws BadRequestException
396 * @throws ForbiddenException
397 * @throws ImagickException
398 * @throws InternalServerErrorException
399 * @throws NotFoundException
400 * @throws UnauthorizedException
402 function prepare_photo_data($type, $scale, $photo_id, $uid)
404 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
405 $data_sql = ($scale === false ? "" : "data, ");
407 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
408 // clients needs to convert this in their way for further processing
409 $r = DBA::toArray(DBA::p(
410 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
411 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
412 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
413 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
414 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
415 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
421 'image/jpeg' => 'jpg',
422 'image/png' => 'png',
426 // prepare output data for photo
427 if (DBA::isResult($r)) {
428 $data = ['photo' => $r[0]];
429 $data['photo']['id'] = $data['photo']['resource-id'];
430 if ($scale !== false) {
431 $data['photo']['data'] = base64_encode($data['photo']['data']);
433 unset($data['photo']['datasize']); //needed only with scale param
435 if ($type == "xml") {
436 $data['photo']['links'] = [];
437 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
438 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
440 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
443 $data['photo']['link'] = [];
444 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
446 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
447 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
451 unset($data['photo']['resource-id']);
452 unset($data['photo']['minscale']);
453 unset($data['photo']['maxscale']);
455 throw new NotFoundException();
458 // retrieve item element for getting activities (like, dislike etc.) related to photo
459 $condition = ['uid' => $uid, 'resource-id' => $photo_id];
460 $item = Post::selectFirst(['id', 'uid', 'uri', 'uri-id', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
461 if (!DBA::isResult($item)) {
462 throw new NotFoundException('Photo-related item not found.');
465 $data['photo']['friendica_activities'] = DI::friendicaActivities()->createFromUriId($item['uri-id'], $item['uid'], $type);
467 // retrieve comments on photo
468 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
469 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
471 $statuses = Post::selectForUser($uid, [], $condition);
473 // prepare output of comments
475 while ($status = DBA::fetch($statuses)) {
476 $commentData[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'])->toArray();
478 DBA::close($statuses);
481 if ($type == "xml") {
483 foreach ($commentData as $comment) {
484 $comments[$k++ . ":comment"] = $comment;
487 foreach ($commentData as $comment) {
488 $comments[] = $comment;
491 $data['photo']['friendica_comments'] = $comments;
493 // include info if rights on photo and rights on item are mismatching
494 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
495 $data['photo']['deny_cid'] != $item['deny_cid'] ||
496 $data['photo']['allow_gid'] != $item['allow_gid'] ||
497 $data['photo']['deny_gid'] != $item['deny_gid'];
498 $data['photo']['rights_mismatch'] = $rights_mismatch;
504 * Add a new group to the database.
506 * @param string $name Group name
507 * @param int $uid User ID
508 * @param array $users List of users to add to the group
511 * @throws BadRequestException
513 function group_create($name, $uid, $users = [])
515 // error if no name specified
517 throw new BadRequestException('group name not specified');
520 // error message if specified group name already exists
521 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
522 throw new BadRequestException('group name already exists');
525 // Check if the group needs to be reactivated
526 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
527 $reactivate_group = true;
531 $ret = Group::create($uid, $name);
533 $gid = Group::getIdByName($uid, $name);
535 throw new BadRequestException('other API error');
539 $erroraddinguser = false;
541 foreach ($users as $user) {
543 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
544 Group::addMember($gid, $cid);
546 $erroraddinguser = true;
547 $errorusers[] = $cid;
551 // return success message incl. missing users in array
552 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
554 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
562 * Returns all lists the user subscribes to.
564 * @param string $type Return type (atom, rss, xml, json)
566 * @return array|string
567 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
569 function api_lists_list($type)
571 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
573 /// @TODO $ret is not filled here?
574 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
577 api_register_func('api/lists/list', 'api_lists_list', true);
578 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
581 * Returns all groups the user owns.
583 * @param string $type Return type (atom, rss, xml, json)
585 * @return array|string
586 * @throws BadRequestException
587 * @throws ForbiddenException
588 * @throws ImagickException
589 * @throws InternalServerErrorException
590 * @throws UnauthorizedException
591 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
593 function api_lists_ownerships($type)
595 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
596 $uid = BaseApi::getCurrentUserID();
599 $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
601 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
603 // loop through all groups
605 foreach ($groups as $group) {
606 if ($group['visible']) {
612 'name' => $group['name'],
613 'id' => intval($group['id']),
614 'id_str' => (string) $group['id'],
615 'user' => $user_info,
619 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
622 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
625 * list all photos of the authenticated user
627 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
628 * @return string|array
629 * @throws ForbiddenException
630 * @throws InternalServerErrorException
632 function api_fr_photos_list($type)
634 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
635 $uid = BaseApi::getCurrentUserID();
637 $r = DBA::toArray(DBA::p(
638 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
639 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
640 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
641 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
644 'image/jpeg' => 'jpg',
645 'image/png' => 'png',
648 $data = ['photo'=>[]];
649 if (DBA::isResult($r)) {
650 foreach ($r as $rr) {
652 $photo['id'] = $rr['resource-id'];
653 $photo['album'] = $rr['album'];
654 $photo['filename'] = $rr['filename'];
655 $photo['type'] = $rr['type'];
656 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
657 $photo['created'] = $rr['created'];
658 $photo['edited'] = $rr['edited'];
659 $photo['desc'] = $rr['desc'];
661 if ($type == "xml") {
662 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
664 $photo['thumb'] = $thumb;
665 $data['photo'][] = $photo;
669 return DI::apiResponse()->formatData("photos", $type, $data);
672 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
675 * upload a new photo or change an existing photo
677 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
678 * @return string|array
679 * @throws BadRequestException
680 * @throws ForbiddenException
681 * @throws ImagickException
682 * @throws InternalServerErrorException
683 * @throws NotFoundException
685 function api_fr_photo_create_update($type)
687 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
688 $uid = BaseApi::getCurrentUserID();
691 $photo_id = $_REQUEST['photo_id'] ?? null;
692 $desc = $_REQUEST['desc'] ?? null;
693 $album = $_REQUEST['album'] ?? null;
694 $album_new = $_REQUEST['album_new'] ?? null;
695 $allow_cid = $_REQUEST['allow_cid'] ?? null;
696 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
697 $allow_gid = $_REQUEST['allow_gid'] ?? null;
698 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
699 // Pictures uploaded via API never get posted as a visible status
700 // See https://github.com/friendica/friendica/issues/10990
703 // do several checks on input parameters
704 // we do not allow calls without album string
705 if ($album == null) {
706 throw new BadRequestException("no albumname specified");
708 // if photo_id == null --> we are uploading a new photo
709 if ($photo_id == null) {
712 // error if no media posted in create-mode
713 if (empty($_FILES['media'])) {
715 throw new BadRequestException("no media data submitted");
718 // album_new will be ignored in create-mode
723 // check if photo is existing in databasei
724 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
725 throw new BadRequestException("photo not available");
729 // checks on acl strings provided by clients
730 $acl_input_error = false;
731 $acl_input_error |= check_acl_input($allow_cid, $uid);
732 $acl_input_error |= check_acl_input($deny_cid, $uid);
733 $acl_input_error |= check_acl_input($allow_gid, $uid);
734 $acl_input_error |= check_acl_input($deny_gid, $uid);
735 if ($acl_input_error) {
736 throw new BadRequestException("acl data invalid");
738 // now let's upload the new media in create-mode
739 if ($mode == "create") {
740 $media = $_FILES['media'];
741 $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);
743 // return success of updating or error message
744 if (!is_null($data)) {
745 return DI::apiResponse()->formatData("photo_create", $type, $data);
747 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
751 // now let's do the changes in update-mode
752 if ($mode == "update") {
753 $updated_fields = [];
755 if (!is_null($desc)) {
756 $updated_fields['desc'] = $desc;
759 if (!is_null($album_new)) {
760 $updated_fields['album'] = $album_new;
763 if (!is_null($allow_cid)) {
764 $allow_cid = trim($allow_cid);
765 $updated_fields['allow_cid'] = $allow_cid;
768 if (!is_null($deny_cid)) {
769 $deny_cid = trim($deny_cid);
770 $updated_fields['deny_cid'] = $deny_cid;
773 if (!is_null($allow_gid)) {
774 $allow_gid = trim($allow_gid);
775 $updated_fields['allow_gid'] = $allow_gid;
778 if (!is_null($deny_gid)) {
779 $deny_gid = trim($deny_gid);
780 $updated_fields['deny_gid'] = $deny_gid;
784 if (count($updated_fields) > 0) {
785 $nothingtodo = false;
786 $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
791 if (!empty($_FILES['media'])) {
792 $nothingtodo = false;
793 $media = $_FILES['media'];
794 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
795 if (!is_null($data)) {
796 return DI::apiResponse()->formatData("photo_update", $type, $data);
800 // return success of updating or error message
802 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
803 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
806 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
807 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
809 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
812 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
815 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true);
816 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true);
819 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
821 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
822 * @return string|array
823 * @throws BadRequestException
824 * @throws ForbiddenException
825 * @throws InternalServerErrorException
826 * @throws NotFoundException
828 function api_fr_photo_detail($type)
830 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
831 $uid = BaseApi::getCurrentUserID();
833 if (empty($_REQUEST['photo_id'])) {
834 throw new BadRequestException("No photo id.");
837 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
838 $photo_id = $_REQUEST['photo_id'];
840 // prepare json/xml output with data from database for the requested photo
841 $data = prepare_photo_data($type, $scale, $photo_id, $uid);
843 return DI::apiResponse()->formatData("photo_detail", $type, $data);
846 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
849 * updates the profile image for the user (either a specified profile or the default profile)
851 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
853 * @return string|array
854 * @throws BadRequestException
855 * @throws ForbiddenException
856 * @throws ImagickException
857 * @throws InternalServerErrorException
858 * @throws NotFoundException
859 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
861 function api_account_update_profile_image($type)
863 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
864 $uid = BaseApi::getCurrentUserID();
867 $profile_id = $_REQUEST['profile_id'] ?? 0;
869 // error if image data is missing
870 if (empty($_FILES['image'])) {
871 throw new BadRequestException("no media data submitted");
874 // check if specified profile id is valid
875 if ($profile_id != 0) {
876 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
877 // error message if specified profile id is not in database
878 if (!DBA::isResult($profile)) {
879 throw new BadRequestException("profile_id not available");
881 $is_default_profile = $profile['is-default'];
883 $is_default_profile = 1;
886 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
888 if (!empty($_FILES['image'])) {
889 $media = $_FILES['image'];
890 } elseif (!empty($_FILES['media'])) {
891 $media = $_FILES['media'];
893 // save new profile image
894 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
897 if (is_array($media['type'])) {
898 $filetype = $media['type'][0];
900 $filetype = $media['type'];
902 if ($filetype == "image/jpeg") {
904 } elseif ($filetype == "image/png") {
907 throw new InternalServerErrorException('Unsupported filetype');
910 // change specified profile or all profiles to the new resource-id
911 if ($is_default_profile) {
912 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
913 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
915 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
916 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
917 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
920 Contact::updateSelfFromUserID($uid, true);
922 // Update global directory in background
923 Profile::publishUpdate($uid);
927 $skip_status = $_REQUEST['skip_status'] ?? false;
929 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
931 // "verified" isn't used here in the standard
932 unset($user_info["verified"]);
934 // "uid" is only needed for some internal stuff, so remove it from here
935 unset($user_info['uid']);
937 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
939 // SaveMediaToDatabase failed for some reason
940 throw new InternalServerErrorException("image upload failed");
944 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true);
947 * Return all or a specified group of the user with the containing contacts.
949 * @param string $type Return type (atom, rss, xml, json)
951 * @return array|string
952 * @throws BadRequestException
953 * @throws ForbiddenException
954 * @throws ImagickException
955 * @throws InternalServerErrorException
956 * @throws UnauthorizedException
958 function api_friendica_group_show($type)
960 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
961 $uid = BaseApi::getCurrentUserID();
964 $gid = $_REQUEST['gid'] ?? 0;
966 // get data of the specified group id or all groups if not specified
968 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
970 // error message if specified gid is not in database
971 if (!DBA::isResult($groups)) {
972 throw new BadRequestException("gid not available");
975 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
978 // loop through all groups and retrieve all members for adding data in the user array
980 foreach ($groups as $rr) {
981 $members = Contact\Group::getById($rr['id']);
984 if ($type == "xml") {
985 $user_element = "users";
987 foreach ($members as $member) {
988 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
989 $users[$k++.":user"] = $user;
992 $user_element = "user";
993 foreach ($members as $member) {
994 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
998 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
1000 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
1003 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
1008 * @param string $type Return type (atom, rss, xml, json)
1010 * @return array|string
1011 * @throws BadRequestException
1012 * @throws ForbiddenException
1013 * @throws ImagickException
1014 * @throws InternalServerErrorException
1015 * @throws UnauthorizedException
1016 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
1018 function api_lists_destroy($type)
1020 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1021 $uid = BaseApi::getCurrentUserID();
1024 $gid = $_REQUEST['list_id'] ?? 0;
1026 // error if no gid specified
1028 throw new BadRequestException('gid not specified');
1031 // get data of the specified group id
1032 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1033 // error message if specified gid is not in database
1035 throw new BadRequestException('gid not available');
1038 if (Group::remove($gid)) {
1040 'name' => $group['name'],
1041 'id' => intval($gid),
1042 'id_str' => (string) $gid,
1043 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1046 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1050 api_register_func('api/lists/destroy', 'api_lists_destroy', true);
1053 * Create the specified group with the posted array of contacts.
1055 * @param string $type Return type (atom, rss, xml, json)
1057 * @return array|string
1058 * @throws BadRequestException
1059 * @throws ForbiddenException
1060 * @throws ImagickException
1061 * @throws InternalServerErrorException
1062 * @throws UnauthorizedException
1064 function api_friendica_group_create($type)
1066 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1067 $uid = BaseApi::getCurrentUserID();
1070 $name = $_REQUEST['name'] ?? '';
1071 $json = json_decode($_POST['json'], true);
1072 $users = $json['user'];
1074 $success = group_create($name, $uid, $users);
1076 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
1079 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true);
1082 * Create a new group.
1084 * @param string $type Return type (atom, rss, xml, json)
1086 * @return array|string
1087 * @throws BadRequestException
1088 * @throws ForbiddenException
1089 * @throws ImagickException
1090 * @throws InternalServerErrorException
1091 * @throws UnauthorizedException
1092 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
1094 function api_lists_create($type)
1096 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1097 $uid = BaseApi::getCurrentUserID();
1100 $name = $_REQUEST['name'] ?? '';
1102 $success = group_create($name, $uid);
1103 if ($success['success']) {
1105 'name' => $success['name'],
1106 'id' => intval($success['gid']),
1107 'id_str' => (string) $success['gid'],
1108 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1111 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
1115 api_register_func('api/lists/create', 'api_lists_create', true);
1118 * Update information about a group.
1120 * @param string $type Return type (atom, rss, xml, json)
1122 * @return array|string
1123 * @throws BadRequestException
1124 * @throws ForbiddenException
1125 * @throws ImagickException
1126 * @throws InternalServerErrorException
1127 * @throws UnauthorizedException
1128 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
1130 function api_lists_update($type)
1132 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1133 $uid = BaseApi::getCurrentUserID();
1136 $gid = $_REQUEST['list_id'] ?? 0;
1137 $name = $_REQUEST['name'] ?? '';
1139 // error if no gid specified
1141 throw new BadRequestException('gid not specified');
1144 // get data of the specified group id
1145 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
1146 // error message if specified gid is not in database
1148 throw new BadRequestException('gid not available');
1151 if (Group::update($gid, $name)) {
1154 'id' => intval($gid),
1155 'id_str' => (string) $gid,
1156 'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1159 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1163 api_register_func('api/lists/update', 'api_lists_update', true);