]> git.mxchange.org Git - friendica.git/blob - include/api.php
API: Direct Messages moved to new place
[friendica.git] / include / api.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  * Friendica implementation of statusnet/twitter API
21  *
22  * @file include/api.php
23  * @todo Automatically detect if incoming data is HTML or BBCode
24  */
25
26 use Friendica\App;
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;
32 use Friendica\DI;
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;
51
52 $API = [];
53
54 /**
55  * Register a function to be the endpoint for defined API path.
56  *
57  * @param string $path   API URL path, relative to DI::baseUrl()
58  * @param string $func   Function name to call on path request
59  */
60 function api_register_func($path, $func)
61 {
62         global $API;
63
64         $API[$path] = [
65                 'func'   => $func,
66         ];
67
68         // Workaround for hotot
69         $path = str_replace("api/", "api/1.1/", $path);
70
71         $API[$path] = [
72                 'func'   => $func,
73         ];
74 }
75
76 /**
77  * Main API entry point
78  *
79  * Authenticate user, call registered API function, set HTTP headers
80  *
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
83  * @throws Exception
84  */
85 function api_call($command, $extension)
86 {
87         global $API;
88
89         Logger::info('Legacy API call', ['command' => $command, 'extension' => $extension]);
90
91         try {
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]);
95
96                                 $stamp =  microtime(true);
97                                 $return = call_user_func($info['func'], $extension);
98                                 $duration = floatval(microtime(true) - $stamp);
99
100                                 Logger::info(BaseApi::LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
101
102                                 DI::profiler()->saveLog(DI::logger(), BaseApi::LOG_PREFIX . 'performance');
103
104                                 if (false === $return) {
105                                         /*
106                                                 * api function returned false withour throw an
107                                                 * exception. This should not happend, throw a 500
108                                                 */
109                                         throw new InternalServerErrorException();
110                                 }
111
112                                 switch ($extension) {
113                                         case "xml":
114                                                 header("Content-Type: text/xml");
115                                                 break;
116                                         case "json":
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 . ")";
122                                                         }
123                                                         $return = $json;
124                                                 }
125                                                 break;
126                                         case "rss":
127                                                 header("Content-Type: application/rss+xml");
128                                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
129                                                 break;
130                                         case "atom":
131                                                 header("Content-Type: application/atom+xml");
132                                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
133                                                 break;
134                                 }
135                                 return $return;
136                         }
137                 }
138
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);
144         }
145 }
146
147 /**
148  *
149  * @param string $acl_string
150  * @param int    $uid
151  * @return bool
152  * @throws Exception
153  */
154 function check_acl_input($acl_string, $uid)
155 {
156         if (empty($acl_string)) {
157                 return false;
158         }
159
160         $contact_not_found = false;
161
162         // split <x><y><z> into array of cid's
163         preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
164
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);
172         }
173         return $contact_not_found;
174 }
175
176 /**
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
189  * @param int     $uid
190  * @return array
191  * @throws BadRequestException
192  * @throws ForbiddenException
193  * @throws ImagickException
194  * @throws InternalServerErrorException
195  * @throws NotFoundException
196  * @throws UnauthorizedException
197  */
198 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype, $visibility, $photo_id, $uid)
199 {
200         $visitor   = 0;
201         $src = "";
202         $filetype = "";
203         $filename = "";
204         $filesize = 0;
205
206         if (is_array($media)) {
207                 if (is_array($media['tmp_name'])) {
208                         $src = $media['tmp_name'][0];
209                 } else {
210                         $src = $media['tmp_name'];
211                 }
212                 if (is_array($media['name'])) {
213                         $filename = basename($media['name'][0]);
214                 } else {
215                         $filename = basename($media['name']);
216                 }
217                 if (is_array($media['size'])) {
218                         $filesize = intval($media['size'][0]);
219                 } else {
220                         $filesize = intval($media['size']);
221                 }
222                 if (is_array($media['type'])) {
223                         $filetype = $media['type'][0];
224                 } else {
225                         $filetype = $media['type'];
226                 }
227         }
228
229         $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
230
231         logger::info(
232                 "File upload src: " . $src . " - filename: " . $filename .
233                 " - size: " . $filesize . " - type: " . $filetype);
234
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");
238         }
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)");
244         }
245
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");
251         }
252
253         // check orientation of image
254         $Image->orient($src);
255         @unlink($src);
256
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);
262         }
263         $width = $Image->getWidth();
264         $height = $Image->getHeight();
265
266         // create a new resource-id if not already provided
267         $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
268
269         if ($mediatype == "photo") {
270                 // upload normal image (scales 0, 1, 2)
271                 logger::info("photo upload: starting new photo upload");
272
273                 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
274                 if (!$r) {
275                         logger::notice("photo upload: image upload with scale 0 (original size) failed");
276                 }
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);
280                         if (!$r) {
281                                 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
282                         }
283                 }
284
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);
288                         if (!$r) {
289                                 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
290                         }
291                 }
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");
296
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);
300                         if (!$r) {
301                                 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
302                         }
303                 }
304
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);
308                         if (!$r) {
309                                 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
310                         }
311                 }
312
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);
316                         if (!$r) {
317                                 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
318                         }
319                 }
320                 $Image->__destruct();
321                 logger::info("photo upload: new profile image upload ended");
322         }
323
324         if (!empty($r)) {
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);
328                 }
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);
331         } else {
332                 throw new InternalServerErrorException("image upload failed");
333                 DI::page()->exit(DI::apiResponse());
334         }
335 }
336
337 /**
338  *
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
346  * @param int     $uid
347  * @throws InternalServerErrorException
348  */
349 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid)
350 {
351         // get data about the api authenticated user
352         $uri = Item::newURI(intval($uid));
353         $owner_record = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
354
355         $arr = [];
356         $arr['guid']          = System::createUUID();
357         $arr['uid']           = $uid;
358         $arr['uri']           = $uri;
359         $arr['post-type']     = Item::PT_IMAGE;
360         $arr['wall']          = 1;
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'];
369         $arr['title']         = '';
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;
375         $arr['origin']        = 1;
376
377         $typetoext = Images::supportedTypes();
378
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]'
382                                 . '[/url]';
383
384         // do the magic for storing the item in the database and trigger the federation to other contacts
385         Item::insert($arr);
386 }
387
388 /**
389  *
390  * @param string $type
391  * @param int    $scale
392  * @param string $photo_id
393  *
394  * @return array
395  * @throws BadRequestException
396  * @throws ForbiddenException
397  * @throws ImagickException
398  * @throws InternalServerErrorException
399  * @throws NotFoundException
400  * @throws UnauthorizedException
401  */
402 function prepare_photo_data($type, $scale, $photo_id, $uid)
403 {
404         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
405         $data_sql = ($scale === false ? "" : "data, ");
406
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`",
416                 $uid,
417                 $photo_id
418         ));
419
420         $typetoext = [
421                 'image/jpeg' => 'jpg',
422                 'image/png' => 'png',
423                 'image/gif' => 'gif'
424         ];
425
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']);
432                 } else {
433                         unset($data['photo']['datasize']); //needed only with scale param
434                 }
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'],
439                                                                                 "scale" => $k,
440                                                                                 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
441                         }
442                 } else {
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
445                         $i = 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']];
448                                 $i++;
449                         }
450                 }
451                 unset($data['photo']['resource-id']);
452                 unset($data['photo']['minscale']);
453                 unset($data['photo']['maxscale']);
454         } else {
455                 throw new NotFoundException();
456         }
457
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.');
463         }
464
465         $data['photo']['friendica_activities'] = DI::friendicaActivities()->createFromUriId($item['uri-id'], $item['uid'], $type);
466
467         // retrieve comments on photo
468         $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
469                 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
470
471         $statuses = Post::selectForUser($uid, [], $condition);
472
473         // prepare output of comments
474         $commentData = [];
475         while ($status = DBA::fetch($statuses)) {
476                 $commentData[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'])->toArray();
477         }
478         DBA::close($statuses);
479
480         $comments = [];
481         if ($type == "xml") {
482                 $k = 0;
483                 foreach ($commentData as $comment) {
484                         $comments[$k++ . ":comment"] = $comment;
485                 }
486         } else {
487                 foreach ($commentData as $comment) {
488                         $comments[] = $comment;
489                 }
490         }
491         $data['photo']['friendica_comments'] = $comments;
492
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;
499
500         return $data;
501 }
502
503 /**
504  * Add a new group to the database.
505  *
506  * @param  string $name  Group name
507  * @param  int    $uid   User ID
508  * @param  array  $users List of users to add to the group
509  *
510  * @return array
511  * @throws BadRequestException
512  */
513 function group_create($name, $uid, $users = [])
514 {
515         // error if no name specified
516         if ($name == "") {
517                 throw new BadRequestException('group name not specified');
518         }
519
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');
523         }
524
525         // Check if the group needs to be reactivated
526         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
527                 $reactivate_group = true;
528         }
529
530         // create group
531         $ret = Group::create($uid, $name);
532         if ($ret) {
533                 $gid = Group::getIdByName($uid, $name);
534         } else {
535                 throw new BadRequestException('other API error');
536         }
537
538         // add members
539         $erroraddinguser = false;
540         $errorusers = [];
541         foreach ($users as $user) {
542                 $cid = $user['cid'];
543                 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
544                         Group::addMember($gid, $cid);
545                 } else {
546                         $erroraddinguser = true;
547                         $errorusers[] = $cid;
548                 }
549         }
550
551         // return success message incl. missing users in array
552         $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
553
554         return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
555 }
556
557 /**
558  * TWITTER API
559  */
560
561 /**
562  * Returns all lists the user subscribes to.
563  *
564  * @param string $type Return type (atom, rss, xml, json)
565  *
566  * @return array|string
567  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
568  */
569 function api_lists_list($type)
570 {
571         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
572         $ret = [];
573         /// @TODO $ret is not filled here?
574         return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
575 }
576
577 api_register_func('api/lists/list', 'api_lists_list', true);
578 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
579
580 /**
581  * Returns all groups the user owns.
582  *
583  * @param string $type Return type (atom, rss, xml, json)
584  *
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
592  */
593 function api_lists_ownerships($type)
594 {
595         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
596         $uid = BaseApi::getCurrentUserID();
597
598         // params
599         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
600
601         $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
602
603         // loop through all groups
604         $lists = [];
605         foreach ($groups as $group) {
606                 if ($group['visible']) {
607                         $mode = 'public';
608                 } else {
609                         $mode = 'private';
610                 }
611                 $lists[] = [
612                         'name' => $group['name'],
613                         'id' => intval($group['id']),
614                         'id_str' => (string) $group['id'],
615                         'user' => $user_info,
616                         'mode' => $mode
617                 ];
618         }
619         return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
620 }
621
622 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
623
624 /**
625  * list all photos of the authenticated user
626  *
627  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
628  * @return string|array
629  * @throws ForbiddenException
630  * @throws InternalServerErrorException
631  */
632 function api_fr_photos_list($type)
633 {
634         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
635         $uid = BaseApi::getCurrentUserID();
636
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
642         ));
643         $typetoext = [
644                 'image/jpeg' => 'jpg',
645                 'image/png' => 'png',
646                 'image/gif' => 'gif'
647         ];
648         $data = ['photo'=>[]];
649         if (DBA::isResult($r)) {
650                 foreach ($r as $rr) {
651                         $photo = [];
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'];
660
661                         if ($type == "xml") {
662                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
663                         } else {
664                                 $photo['thumb'] = $thumb;
665                                 $data['photo'][] = $photo;
666                         }
667                 }
668         }
669         return DI::apiResponse()->formatData("photos", $type, $data);
670 }
671
672 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
673
674 /**
675  * upload a new photo or change an existing photo
676  *
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
684  */
685 function api_fr_photo_create_update($type)
686 {
687         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
688         $uid = BaseApi::getCurrentUserID();
689
690         // input params
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
701         $visibility = false;
702
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");
707         }
708         // if photo_id == null --> we are uploading a new photo
709         if ($photo_id == null) {
710                 $mode = "create";
711
712                 // error if no media posted in create-mode
713                 if (empty($_FILES['media'])) {
714                         // Output error
715                         throw new BadRequestException("no media data submitted");
716                 }
717
718                 // album_new will be ignored in create-mode
719                 $album_new = "";
720         } else {
721                 $mode = "update";
722
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");
726                 }
727         }
728
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");
737         }
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);
742
743                 // return success of updating or error message
744                 if (!is_null($data)) {
745                         return DI::apiResponse()->formatData("photo_create", $type, $data);
746                 } else {
747                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
748                 }
749         }
750
751         // now let's do the changes in update-mode
752         if ($mode == "update") {
753                 $updated_fields = [];
754
755                 if (!is_null($desc)) {
756                         $updated_fields['desc'] = $desc;
757                 }
758
759                 if (!is_null($album_new)) {
760                         $updated_fields['album'] = $album_new;
761                 }
762
763                 if (!is_null($allow_cid)) {
764                         $allow_cid = trim($allow_cid);
765                         $updated_fields['allow_cid'] = $allow_cid;
766                 }
767
768                 if (!is_null($deny_cid)) {
769                         $deny_cid = trim($deny_cid);
770                         $updated_fields['deny_cid'] = $deny_cid;
771                 }
772
773                 if (!is_null($allow_gid)) {
774                         $allow_gid = trim($allow_gid);
775                         $updated_fields['allow_gid'] = $allow_gid;
776                 }
777
778                 if (!is_null($deny_gid)) {
779                         $deny_gid = trim($deny_gid);
780                         $updated_fields['deny_gid'] = $deny_gid;
781                 }
782
783                 $result = false;
784                 if (count($updated_fields) > 0) {
785                         $nothingtodo = false;
786                         $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
787                 } else {
788                         $nothingtodo = true;
789                 }
790
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);
797                         }
798                 }
799
800                 // return success of updating or error message
801                 if ($result) {
802                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
803                         return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
804                 } else {
805                         if ($nothingtodo) {
806                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
807                                 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
808                         }
809                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
810                 }
811         }
812         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
813 }
814
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);
817
818 /**
819  * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
820  *
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
827  */
828 function api_fr_photo_detail($type)
829 {
830         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
831         $uid = BaseApi::getCurrentUserID();
832
833         if (empty($_REQUEST['photo_id'])) {
834                 throw new BadRequestException("No photo id.");
835         }
836
837         $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
838         $photo_id = $_REQUEST['photo_id'];
839
840         // prepare json/xml output with data from database for the requested photo
841         $data = prepare_photo_data($type, $scale, $photo_id, $uid);
842
843         return DI::apiResponse()->formatData("photo_detail", $type, $data);
844 }
845
846 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
847
848 /**
849  * updates the profile image for the user (either a specified profile or the default profile)
850  *
851  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
852  *
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
860  */
861 function api_account_update_profile_image($type)
862 {
863         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
864         $uid = BaseApi::getCurrentUserID();
865
866         // input params
867         $profile_id = $_REQUEST['profile_id'] ?? 0;
868
869         // error if image data is missing
870         if (empty($_FILES['image'])) {
871                 throw new BadRequestException("no media data submitted");
872         }
873
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");
880                 }
881                 $is_default_profile = $profile['is-default'];
882         } else {
883                 $is_default_profile = 1;
884         }
885
886         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
887         $media = null;
888         if (!empty($_FILES['image'])) {
889                 $media = $_FILES['image'];
890         } elseif (!empty($_FILES['media'])) {
891                 $media = $_FILES['media'];
892         }
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);
895
896         // get filetype
897         if (is_array($media['type'])) {
898                 $filetype = $media['type'][0];
899         } else {
900                 $filetype = $media['type'];
901         }
902         if ($filetype == "image/jpeg") {
903                 $fileext = "jpg";
904         } elseif ($filetype == "image/png") {
905                 $fileext = "png";
906         } else {
907                 throw new InternalServerErrorException('Unsupported filetype');
908         }
909
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);
914         } else {
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]);
918         }
919
920         Contact::updateSelfFromUserID($uid, true);
921
922         // Update global directory in background
923         Profile::publishUpdate($uid);
924
925         // output for client
926         if ($data) {
927                 $skip_status = $_REQUEST['skip_status'] ?? false;
928
929                 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
930
931                 // "verified" isn't used here in the standard
932                 unset($user_info["verified"]);
933
934                 // "uid" is only needed for some internal stuff, so remove it from here
935                 unset($user_info['uid']);
936
937                 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
938         } else {
939                 // SaveMediaToDatabase failed for some reason
940                 throw new InternalServerErrorException("image upload failed");
941         }
942 }
943
944 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true);
945
946 /**
947  * Return all or a specified group of the user with the containing contacts.
948  *
949  * @param string $type Return type (atom, rss, xml, json)
950  *
951  * @return array|string
952  * @throws BadRequestException
953  * @throws ForbiddenException
954  * @throws ImagickException
955  * @throws InternalServerErrorException
956  * @throws UnauthorizedException
957  */
958 function api_friendica_group_show($type)
959 {
960         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
961         $uid = BaseApi::getCurrentUserID();
962
963         // params
964         $gid = $_REQUEST['gid'] ?? 0;
965
966         // get data of the specified group id or all groups if not specified
967         if ($gid != 0) {
968                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
969
970                 // error message if specified gid is not in database
971                 if (!DBA::isResult($groups)) {
972                         throw new BadRequestException("gid not available");
973                 }
974         } else {
975                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
976         }
977
978         // loop through all groups and retrieve all members for adding data in the user array
979         $grps = [];
980         foreach ($groups as $rr) {
981                 $members = Contact\Group::getById($rr['id']);
982                 $users = [];
983
984                 if ($type == "xml") {
985                         $user_element = "users";
986                         $k = 0;
987                         foreach ($members as $member) {
988                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
989                                 $users[$k++.":user"] = $user;
990                         }
991                 } else {
992                         $user_element = "user";
993                         foreach ($members as $member) {
994                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
995                                 $users[] = $user;
996                         }
997                 }
998                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
999         }
1000         return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
1001 }
1002
1003 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
1004
1005 /**
1006  * Delete a group.
1007  *
1008  * @param string $type Return type (atom, rss, xml, json)
1009  *
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
1017  */
1018 function api_lists_destroy($type)
1019 {
1020         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1021         $uid = BaseApi::getCurrentUserID();
1022
1023         // params
1024         $gid = $_REQUEST['list_id'] ?? 0;
1025
1026         // error if no gid specified
1027         if ($gid == 0) {
1028                 throw new BadRequestException('gid not specified');
1029         }
1030
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
1034         if (!$group) {
1035                 throw new BadRequestException('gid not available');
1036         }
1037
1038         if (Group::remove($gid)) {
1039                 $list = [
1040                         'name' => $group['name'],
1041                         'id' => intval($gid),
1042                         'id_str' => (string) $gid,
1043                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1044                 ];
1045
1046                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1047         }
1048 }
1049
1050 api_register_func('api/lists/destroy', 'api_lists_destroy', true);
1051
1052 /**
1053  * Create the specified group with the posted array of contacts.
1054  *
1055  * @param string $type Return type (atom, rss, xml, json)
1056  *
1057  * @return array|string
1058  * @throws BadRequestException
1059  * @throws ForbiddenException
1060  * @throws ImagickException
1061  * @throws InternalServerErrorException
1062  * @throws UnauthorizedException
1063  */
1064 function api_friendica_group_create($type)
1065 {
1066         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1067         $uid = BaseApi::getCurrentUserID();
1068
1069         // params
1070         $name = $_REQUEST['name'] ?? '';
1071         $json = json_decode($_POST['json'], true);
1072         $users = $json['user'];
1073
1074         $success = group_create($name, $uid, $users);
1075
1076         return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
1077 }
1078
1079 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true);
1080
1081 /**
1082  * Create a new group.
1083  *
1084  * @param string $type Return type (atom, rss, xml, json)
1085  *
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
1093  */
1094 function api_lists_create($type)
1095 {
1096         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1097         $uid = BaseApi::getCurrentUserID();
1098
1099         // params
1100         $name = $_REQUEST['name'] ?? '';
1101
1102         $success = group_create($name, $uid);
1103         if ($success['success']) {
1104                 $grp = [
1105                         'name' => $success['name'],
1106                         'id' => intval($success['gid']),
1107                         'id_str' => (string) $success['gid'],
1108                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1109                 ];
1110
1111                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
1112         }
1113 }
1114
1115 api_register_func('api/lists/create', 'api_lists_create', true);
1116
1117 /**
1118  * Update information about a group.
1119  *
1120  * @param string $type Return type (atom, rss, xml, json)
1121  *
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
1129  */
1130 function api_lists_update($type)
1131 {
1132         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1133         $uid = BaseApi::getCurrentUserID();
1134
1135         // params
1136         $gid = $_REQUEST['list_id'] ?? 0;
1137         $name = $_REQUEST['name'] ?? '';
1138
1139         // error if no gid specified
1140         if ($gid == 0) {
1141                 throw new BadRequestException('gid not specified');
1142         }
1143
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
1147         if (!$group) {
1148                 throw new BadRequestException('gid not available');
1149         }
1150
1151         if (Group::update($gid, $name)) {
1152                 $list = [
1153                         'name' => $name,
1154                         'id' => intval($gid),
1155                         'id_str' => (string) $gid,
1156                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
1157                 ];
1158
1159                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
1160         }
1161 }
1162
1163 api_register_func('api/lists/update', 'api_lists_update', true);