]> git.mxchange.org Git - friendica.git/blob - include/api.php
Lists and tweet search moved
[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\Protocol;
31 use Friendica\Core\System;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Group;
36 use Friendica\Model\Item;
37 use Friendica\Model\Mail;
38 use Friendica\Model\Notification;
39 use Friendica\Model\Photo;
40 use Friendica\Model\Post;
41 use Friendica\Model\Profile;
42 use Friendica\Model\User;
43 use Friendica\Module\BaseApi;
44 use Friendica\Network\HTTPException;
45 use Friendica\Network\HTTPException\BadRequestException;
46 use Friendica\Network\HTTPException\ForbiddenException;
47 use Friendica\Network\HTTPException\InternalServerErrorException;
48 use Friendica\Network\HTTPException\NotFoundException;
49 use Friendica\Network\HTTPException\TooManyRequestsException;
50 use Friendica\Network\HTTPException\UnauthorizedException;
51 use Friendica\Object\Image;
52 use Friendica\Security\BasicAuth;
53 use Friendica\Util\DateTimeFormat;
54 use Friendica\Util\Images;
55 use Friendica\Util\Network;
56 use Friendica\Util\Strings;
57
58 require_once __DIR__ . '/../mod/item.php';
59 require_once __DIR__ . '/../mod/wall_upload.php';
60
61 define('API_METHOD_ANY', '*');
62 define('API_METHOD_GET', 'GET');
63 define('API_METHOD_POST', 'POST,PUT');
64 define('API_METHOD_DELETE', 'POST,DELETE');
65
66 define('API_LOG_PREFIX', 'API {action} - ');
67
68 $API = [];
69
70 /**
71  * Register a function to be the endpoint for defined API path.
72  *
73  * @param string $path   API URL path, relative to DI::baseUrl()
74  * @param string $func   Function name to call on path request
75  * @param bool   $auth   API need logged user
76  * @param string $method HTTP method reqiured to call this endpoint.
77  *                       One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
78  *                       Default to API_METHOD_ANY
79  */
80 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
81 {
82         global $API;
83
84         $API[$path] = [
85                 'func'   => $func,
86                 'auth'   => $auth,
87                 'method' => $method,
88         ];
89
90         // Workaround for hotot
91         $path = str_replace("api/", "api/1.1/", $path);
92
93         $API[$path] = [
94                 'func'   => $func,
95                 'auth'   => $auth,
96                 'method' => $method,
97         ];
98 }
99
100 /**
101  * Main API entry point
102  *
103  * Authenticate user, call registered API function, set HTTP headers
104  *
105  * @param App $a App
106  * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
107  * @return string|array API call result
108  * @throws Exception
109  */
110 function api_call(App $a, App\Arguments $args = null)
111 {
112         global $API;
113
114         if ($args == null) {
115                 $args = DI::args();
116         }
117
118         $type = "json";
119         if (strpos($args->getCommand(), ".xml") > 0) {
120                 $type = "xml";
121         }
122         if (strpos($args->getCommand(), ".json") > 0) {
123                 $type = "json";
124         }
125         if (strpos($args->getCommand(), ".rss") > 0) {
126                 $type = "rss";
127         }
128         if (strpos($args->getCommand(), ".atom") > 0) {
129                 $type = "atom";
130         }
131
132         try {
133                 foreach ($API as $p => $info) {
134                         if (strpos($args->getCommand(), $p) === 0) {
135                                 if (!empty($info['auth']) && BaseApi::getCurrentUserID() === false) {
136                                         BasicAuth::getCurrentUserID(true);
137                                         Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
138                                 }
139
140                                 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
141
142                                 $stamp =  microtime(true);
143                                 $return = call_user_func($info['func'], $type);
144                                 $duration = floatval(microtime(true) - $stamp);
145
146                                 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
147
148                                 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
149
150                                 if (false === $return) {
151                                         /*
152                                                 * api function returned false withour throw an
153                                                 * exception. This should not happend, throw a 500
154                                                 */
155                                         throw new InternalServerErrorException();
156                                 }
157
158                                 switch ($type) {
159                                         case "xml":
160                                                 header("Content-Type: text/xml");
161                                                 break;
162                                         case "json":
163                                                 header("Content-Type: application/json");
164                                                 if (!empty($return)) {
165                                                         $json = json_encode(end($return));
166                                                         if (!empty($_GET['callback'])) {
167                                                                 $json = $_GET['callback'] . "(" . $json . ")";
168                                                         }
169                                                         $return = $json;
170                                                 }
171                                                 break;
172                                         case "rss":
173                                                 header("Content-Type: application/rss+xml");
174                                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
175                                                 break;
176                                         case "atom":
177                                                 header("Content-Type: application/atom+xml");
178                                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
179                                                 break;
180                                 }
181                                 return $return;
182                         }
183                 }
184
185                 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
186                 throw new NotFoundException();
187         } catch (HTTPException $e) {
188                 Logger::notice(API_LOG_PREFIX . 'got exception', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString(), 'error' => $e]);
189                 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
190         }
191 }
192
193 /**
194  *
195  * @param array $item
196  * @param array $recipient
197  * @param array $sender
198  *
199  * @return array
200  * @throws InternalServerErrorException
201  */
202 function api_format_messages($item, $recipient, $sender)
203 {
204         // standard meta information
205         $ret = [
206                 'id'                    => $item['id'],
207                 'sender_id'             => $sender['id'],
208                 'text'                  => "",
209                 'recipient_id'          => $recipient['id'],
210                 'created_at'            => DateTimeFormat::utc($item['created'] ?? 'now', DateTimeFormat::API),
211                 'sender_screen_name'    => $sender['screen_name'],
212                 'recipient_screen_name' => $recipient['screen_name'],
213                 'sender'                => $sender,
214                 'recipient'             => $recipient,
215                 'title'                 => "",
216                 'friendica_seen'        => $item['seen'] ?? 0,
217                 'friendica_parent_uri'  => $item['parent-uri'] ?? '',
218         ];
219
220         // "uid" is only needed for some internal stuff, so remove it from here
221         if (isset($ret['sender']['uid'])) {
222                 unset($ret['sender']['uid']);
223         }
224         if (isset($ret['recipient']['uid'])) {
225                 unset($ret['recipient']['uid']);
226         }
227
228         //don't send title to regular StatusNET requests to avoid confusing these apps
229         if (!empty($_GET['getText'])) {
230                 $ret['title'] = $item['title'];
231                 if ($_GET['getText'] == 'html') {
232                         $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
233                 } elseif ($_GET['getText'] == 'plain') {
234                         $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
235                 }
236         } else {
237                 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
238         }
239         if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
240                 unset($ret['sender']);
241                 unset($ret['recipient']);
242         }
243
244         return $ret;
245 }
246
247 /**
248  *
249  * @param string $acl_string
250  * @param int    $uid
251  * @return bool
252  * @throws Exception
253  */
254 function check_acl_input($acl_string, $uid)
255 {
256         if (empty($acl_string)) {
257                 return false;
258         }
259
260         $contact_not_found = false;
261
262         // split <x><y><z> into array of cid's
263         preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
264
265         // check for each cid if it is available on server
266         $cid_array = $array[0];
267         foreach ($cid_array as $cid) {
268                 $cid = str_replace("<", "", $cid);
269                 $cid = str_replace(">", "", $cid);
270                 $condition = ['id' => $cid, 'uid' => $uid];
271                 $contact_not_found |= !DBA::exists('contact', $condition);
272         }
273         return $contact_not_found;
274 }
275
276 /**
277  * @param string  $mediatype
278  * @param array   $media
279  * @param string  $type
280  * @param string  $album
281  * @param string  $allow_cid
282  * @param string  $deny_cid
283  * @param string  $allow_gid
284  * @param string  $deny_gid
285  * @param string  $desc
286  * @param integer $phototype
287  * @param boolean $visibility
288  * @param string  $photo_id
289  * @param int     $uid
290  * @return array
291  * @throws BadRequestException
292  * @throws ForbiddenException
293  * @throws ImagickException
294  * @throws InternalServerErrorException
295  * @throws NotFoundException
296  * @throws UnauthorizedException
297  */
298 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype, $visibility, $photo_id, $uid)
299 {
300         $visitor   = 0;
301         $src = "";
302         $filetype = "";
303         $filename = "";
304         $filesize = 0;
305
306         if (is_array($media)) {
307                 if (is_array($media['tmp_name'])) {
308                         $src = $media['tmp_name'][0];
309                 } else {
310                         $src = $media['tmp_name'];
311                 }
312                 if (is_array($media['name'])) {
313                         $filename = basename($media['name'][0]);
314                 } else {
315                         $filename = basename($media['name']);
316                 }
317                 if (is_array($media['size'])) {
318                         $filesize = intval($media['size'][0]);
319                 } else {
320                         $filesize = intval($media['size']);
321                 }
322                 if (is_array($media['type'])) {
323                         $filetype = $media['type'][0];
324                 } else {
325                         $filetype = $media['type'];
326                 }
327         }
328
329         $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
330
331         logger::info(
332                 "File upload src: " . $src . " - filename: " . $filename .
333                 " - size: " . $filesize . " - type: " . $filetype);
334
335         // check if there was a php upload error
336         if ($filesize == 0 && $media['error'] == 1) {
337                 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
338         }
339         // check against max upload size within Friendica instance
340         $maximagesize = DI::config()->get('system', 'maximagesize');
341         if ($maximagesize && ($filesize > $maximagesize)) {
342                 $formattedBytes = Strings::formatBytes($maximagesize);
343                 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
344         }
345
346         // create Photo instance with the data of the image
347         $imagedata = @file_get_contents($src);
348         $Image = new Image($imagedata, $filetype);
349         if (!$Image->isValid()) {
350                 throw new InternalServerErrorException("unable to process image data");
351         }
352
353         // check orientation of image
354         $Image->orient($src);
355         @unlink($src);
356
357         // check max length of images on server
358         $max_length = DI::config()->get('system', 'max_image_length');
359         if ($max_length > 0) {
360                 $Image->scaleDown($max_length);
361                 logger::info("File upload: Scaling picture to new size " . $max_length);
362         }
363         $width = $Image->getWidth();
364         $height = $Image->getHeight();
365
366         // create a new resource-id if not already provided
367         $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
368
369         if ($mediatype == "photo") {
370                 // upload normal image (scales 0, 1, 2)
371                 logger::info("photo upload: starting new photo upload");
372
373                 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
374                 if (!$r) {
375                         logger::notice("photo upload: image upload with scale 0 (original size) failed");
376                 }
377                 if ($width > 640 || $height > 640) {
378                         $Image->scaleDown(640);
379                         $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
380                         if (!$r) {
381                                 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
382                         }
383                 }
384
385                 if ($width > 320 || $height > 320) {
386                         $Image->scaleDown(320);
387                         $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
388                         if (!$r) {
389                                 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
390                         }
391                 }
392                 logger::info("photo upload: new photo upload ended");
393         } elseif ($mediatype == "profileimage") {
394                 // upload profile image (scales 4, 5, 6)
395                 logger::info("photo upload: starting new profile image upload");
396
397                 if ($width > 300 || $height > 300) {
398                         $Image->scaleDown(300);
399                         $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
400                         if (!$r) {
401                                 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
402                         }
403                 }
404
405                 if ($width > 80 || $height > 80) {
406                         $Image->scaleDown(80);
407                         $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
408                         if (!$r) {
409                                 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
410                         }
411                 }
412
413                 if ($width > 48 || $height > 48) {
414                         $Image->scaleDown(48);
415                         $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
416                         if (!$r) {
417                                 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
418                         }
419                 }
420                 $Image->__destruct();
421                 logger::info("photo upload: new profile image upload ended");
422         }
423
424         if (!empty($r)) {
425                 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
426                 if ($photo_id == null && $mediatype == "photo") {
427                         post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid);
428                 }
429                 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
430                 return prepare_photo_data($type, false, $resource_id, $uid);
431         } else {
432                 throw new InternalServerErrorException("image upload failed");
433         }
434 }
435
436 /**
437  *
438  * @param string  $hash
439  * @param string  $allow_cid
440  * @param string  $deny_cid
441  * @param string  $allow_gid
442  * @param string  $deny_gid
443  * @param string  $filetype
444  * @param boolean $visibility
445  * @param int     $uid
446  * @throws InternalServerErrorException
447  */
448 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid)
449 {
450         // get data about the api authenticated user
451         $uri = Item::newURI(intval($uid));
452         $owner_record = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
453
454         $arr = [];
455         $arr['guid']          = System::createUUID();
456         $arr['uid']           = intval($uid);
457         $arr['uri']           = $uri;
458         $arr['type']          = 'photo';
459         $arr['wall']          = 1;
460         $arr['resource-id']   = $hash;
461         $arr['contact-id']    = $owner_record['id'];
462         $arr['owner-name']    = $owner_record['name'];
463         $arr['owner-link']    = $owner_record['url'];
464         $arr['owner-avatar']  = $owner_record['thumb'];
465         $arr['author-name']   = $owner_record['name'];
466         $arr['author-link']   = $owner_record['url'];
467         $arr['author-avatar'] = $owner_record['thumb'];
468         $arr['title']         = "";
469         $arr['allow_cid']     = $allow_cid;
470         $arr['allow_gid']     = $allow_gid;
471         $arr['deny_cid']      = $deny_cid;
472         $arr['deny_gid']      = $deny_gid;
473         $arr['visible']       = $visibility;
474         $arr['origin']        = 1;
475
476         $typetoext = [
477                         'image/jpeg' => 'jpg',
478                         'image/png' => 'png',
479                         'image/gif' => 'gif'
480                         ];
481
482         // adds link to the thumbnail scale photo
483         $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
484                                 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
485                                 . '[/url]';
486
487         // do the magic for storing the item in the database and trigger the federation to other contacts
488         Item::insert($arr);
489 }
490
491 /**
492  *
493  * @param string $type
494  * @param int    $scale
495  * @param string $photo_id
496  *
497  * @return array
498  * @throws BadRequestException
499  * @throws ForbiddenException
500  * @throws ImagickException
501  * @throws InternalServerErrorException
502  * @throws NotFoundException
503  * @throws UnauthorizedException
504  */
505 function prepare_photo_data($type, $scale, $photo_id, $uid)
506 {
507         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
508         $data_sql = ($scale === false ? "" : "data, ");
509
510         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
511         // clients needs to convert this in their way for further processing
512         $r = DBA::toArray(DBA::p(
513                 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
514                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
515                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
516                         FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
517                                    `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
518                                    `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
519                 $uid,
520                 $photo_id
521         ));
522
523         $typetoext = [
524                 'image/jpeg' => 'jpg',
525                 'image/png' => 'png',
526                 'image/gif' => 'gif'
527         ];
528
529         // prepare output data for photo
530         if (DBA::isResult($r)) {
531                 $data = ['photo' => $r[0]];
532                 $data['photo']['id'] = $data['photo']['resource-id'];
533                 if ($scale !== false) {
534                         $data['photo']['data'] = base64_encode($data['photo']['data']);
535                 } else {
536                         unset($data['photo']['datasize']); //needed only with scale param
537                 }
538                 if ($type == "xml") {
539                         $data['photo']['links'] = [];
540                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
541                                 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
542                                                                                 "scale" => $k,
543                                                                                 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
544                         }
545                 } else {
546                         $data['photo']['link'] = [];
547                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
548                         $i = 0;
549                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
550                                 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
551                                 $i++;
552                         }
553                 }
554                 unset($data['photo']['resource-id']);
555                 unset($data['photo']['minscale']);
556                 unset($data['photo']['maxscale']);
557         } else {
558                 throw new NotFoundException();
559         }
560
561         // retrieve item element for getting activities (like, dislike etc.) related to photo
562         $condition = ['uid' => $uid, 'resource-id' => $photo_id];
563         $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
564         if (!DBA::isResult($item)) {
565                 throw new NotFoundException('Photo-related item not found.');
566         }
567
568         $data['photo']['friendica_activities'] = DI::friendicaActivities()->createFromUriId($item['uri-id'], $item['uid'], $type);
569
570         // retrieve comments on photo
571         $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
572                 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
573
574         $statuses = Post::selectForUser($uid, [], $condition);
575
576         // prepare output of comments
577         $commentData = [];
578         while ($status = DBA::fetch($statuses)) {
579                 $commentData[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'])->toArray();
580         }
581         DBA::close($statuses);
582
583         $comments = [];
584         if ($type == "xml") {
585                 $k = 0;
586                 foreach ($commentData as $comment) {
587                         $comments[$k++ . ":comment"] = $comment;
588                 }
589         } else {
590                 foreach ($commentData as $comment) {
591                         $comments[] = $comment;
592                 }
593         }
594         $data['photo']['friendica_comments'] = $comments;
595
596         // include info if rights on photo and rights on item are mismatching
597         $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
598                 $data['photo']['deny_cid'] != $item['deny_cid'] ||
599                 $data['photo']['allow_gid'] != $item['allow_gid'] ||
600                 $data['photo']['deny_gid'] != $item['deny_gid'];
601         $data['photo']['rights_mismatch'] = $rights_mismatch;
602
603         return $data;
604 }
605
606 /**
607  *
608  * @param string $text
609  *
610  * @return string
611  * @throws InternalServerErrorException
612  */
613 function api_clean_plain_items($text)
614 {
615         $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
616
617         $text = BBCode::cleanPictureLinks($text);
618         $URLSearchString = "^\[\]";
619
620         $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
621
622         if ($include_entities == "true") {
623                 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
624         }
625
626         // Simplify "attachment" element
627         $text = BBCode::removeAttachment($text);
628
629         return $text;
630 }
631
632 /**
633  * Add a new group to the database.
634  *
635  * @param  string $name  Group name
636  * @param  int    $uid   User ID
637  * @param  array  $users List of users to add to the group
638  *
639  * @return array
640  * @throws BadRequestException
641  */
642 function group_create($name, $uid, $users = [])
643 {
644         // error if no name specified
645         if ($name == "") {
646                 throw new BadRequestException('group name not specified');
647         }
648
649         // error message if specified group name already exists
650         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
651                 throw new BadRequestException('group name already exists');
652         }
653
654         // Check if the group needs to be reactivated
655         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
656                 $reactivate_group = true;
657         }
658
659         // create group
660         $ret = Group::create($uid, $name);
661         if ($ret) {
662                 $gid = Group::getIdByName($uid, $name);
663         } else {
664                 throw new BadRequestException('other API error');
665         }
666
667         // add members
668         $erroraddinguser = false;
669         $errorusers = [];
670         foreach ($users as $user) {
671                 $cid = $user['cid'];
672                 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
673                         Group::addMember($gid, $cid);
674                 } else {
675                         $erroraddinguser = true;
676                         $errorusers[] = $cid;
677                 }
678         }
679
680         // return success message incl. missing users in array
681         $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
682
683         return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
684 }
685
686 /**
687  * TWITTER API
688  */
689
690 /**
691  * Deprecated function to upload media.
692  *
693  * @param string $type Return type (atom, rss, xml, json)
694  *
695  * @return array|string
696  * @throws BadRequestException
697  * @throws ForbiddenException
698  * @throws ImagickException
699  * @throws InternalServerErrorException
700  * @throws UnauthorizedException
701  */
702 function api_statuses_mediap($type)
703 {
704         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
705         $uid = BaseApi::getCurrentUserID();
706
707         $a = DI::app();
708
709         $_REQUEST['profile_uid'] = $uid;
710         $_REQUEST['api_source'] = true;
711         $txt = $_REQUEST['status'] ?? '';
712
713         if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
714                 $txt = HTML::toBBCodeVideo($txt);
715                 $config = HTMLPurifier_Config::createDefault();
716                 $config->set('Cache.DefinitionImpl', null);
717                 $purifier = new HTMLPurifier($config);
718                 $txt = $purifier->purify($txt);
719         }
720         $txt = HTML::toBBCode($txt);
721
722         $picture = wall_upload_post($a, false);
723
724         // now that we have the img url in bbcode we can add it to the status and insert the wall item.
725         $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
726         $item_id = item_post($a);
727
728         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
729
730         // output the post that we just posted.
731         $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
732         return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
733 }
734
735 /// @TODO move this to top of file or somewhere better!
736 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
737
738 /**
739  * Updates the user’s current status.
740  *
741  * @param string $type Return type (atom, rss, xml, json)
742  *
743  * @return array|string
744  * @throws BadRequestException
745  * @throws ForbiddenException
746  * @throws ImagickException
747  * @throws InternalServerErrorException
748  * @throws TooManyRequestsException
749  * @throws UnauthorizedException
750  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
751  */
752 function api_statuses_update($type)
753 {
754         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
755         $uid = BaseApi::getCurrentUserID();
756
757         $a = DI::app();
758
759         // convert $_POST array items to the form we use for web posts.
760         if (!empty($_REQUEST['htmlstatus'])) {
761                 $txt = $_REQUEST['htmlstatus'];
762                 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
763                         $txt = HTML::toBBCodeVideo($txt);
764
765                         $config = HTMLPurifier_Config::createDefault();
766                         $config->set('Cache.DefinitionImpl', null);
767
768                         $purifier = new HTMLPurifier($config);
769                         $txt = $purifier->purify($txt);
770
771                         $_REQUEST['body'] = HTML::toBBCode($txt);
772                 }
773         } else {
774                 $_REQUEST['body'] = $_REQUEST['status'] ?? null;
775         }
776
777         $_REQUEST['title'] = $_REQUEST['title'] ?? null;
778
779         $parent = $_REQUEST['in_reply_to_status_id'] ?? null;
780
781         // Twidere sends "-1" if it is no reply ...
782         if ($parent == -1) {
783                 $parent = "";
784         }
785
786         if (ctype_digit($parent)) {
787                 $_REQUEST['parent'] = $parent;
788         } else {
789                 $_REQUEST['parent_uri'] = $parent;
790         }
791
792         if (!empty($_REQUEST['lat']) && !empty($_REQUEST['long'])) {
793                 $_REQUEST['coord'] = sprintf("%s %s", $_REQUEST['lat'], $_REQUEST['long']);
794         }
795         $_REQUEST['profile_uid'] = $uid;
796
797         if (!$parent) {
798                 // Check for throttling (maximum posts per day, week and month)
799                 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
800                 if ($throttle_day > 0) {
801                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
802
803                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
804                         $posts_day = Post::count($condition);
805
806                         if ($posts_day > $throttle_day) {
807                                 logger::info('Daily posting limit reached for user ' . $uid);
808                                 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
809                                 throw new TooManyRequestsException(DI::l10n()->tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
810                         }
811                 }
812
813                 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
814                 if ($throttle_week > 0) {
815                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
816
817                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
818                         $posts_week = Post::count($condition);
819
820                         if ($posts_week > $throttle_week) {
821                                 logger::info('Weekly posting limit reached for user ' . $uid);
822                                 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
823                                 throw new TooManyRequestsException(DI::l10n()->tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
824                         }
825                 }
826
827                 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
828                 if ($throttle_month > 0) {
829                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
830
831                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
832                         $posts_month = Post::count($condition);
833
834                         if ($posts_month > $throttle_month) {
835                                 logger::info('Monthly posting limit reached for user ' . $uid);
836                                 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
837                                 throw new TooManyRequestsException(DI::l10n()->t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
838                         }
839                 }
840         }
841
842         if (!empty($_REQUEST['media_ids'])) {
843                 $ids = explode(',', $_REQUEST['media_ids']);
844         } elseif (!empty($_FILES['media'])) {
845                 // upload the image if we have one
846                 $picture = wall_upload_post($a, false);
847                 if (is_array($picture)) {
848                         $ids[] = $picture['id'];
849                 }
850         }
851
852         $attachments = [];
853         $ressources = [];
854
855         if (!empty($ids)) {
856                 foreach ($ids as $id) {
857                         $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
858                                         INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
859                                                 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
860                                         ORDER BY `photo`.`width` DESC LIMIT 2", $id, $uid));
861
862                         if (!empty($media)) {
863                                 $ressources[] = $media[0]['resource-id'];
864                                 $phototypes = Images::supportedTypes();
865                                 $ext = $phototypes[$media[0]['type']];
866
867                                 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
868                                         'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
869                                         'size' => $media[0]['datasize'],
870                                         'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
871                                         'description' => $media[0]['desc'] ?? '',
872                                         'width' => $media[0]['width'],
873                                         'height' => $media[0]['height']];
874
875                                 if (count($media) > 1) {
876                                         $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
877                                         $attachment['preview-width'] = $media[1]['width'];
878                                         $attachment['preview-height'] = $media[1]['height'];
879                                 }
880                                 $attachments[] = $attachment;
881                         }
882                 }
883
884                 // We have to avoid that the post is rejected because of an empty body
885                 if (empty($_REQUEST['body'])) {
886                         $_REQUEST['body'] = '[hr]';
887                 }
888         }
889
890         if (!empty($attachments)) {
891                 $_REQUEST['attachments'] = $attachments;
892         }
893
894         // set this so that the item_post() function is quiet and doesn't redirect or emit json
895
896         $_REQUEST['api_source'] = true;
897
898         if (empty($_REQUEST['source'])) {
899                 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
900         }
901
902         // call out normal post function
903         $item_id = item_post($a);
904
905         if (!empty($ressources) && !empty($item_id)) {
906                 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
907                 foreach ($ressources as $ressource) {
908                         Photo::setPermissionForRessource($ressource, $uid, $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
909                 }
910         }
911
912         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
913
914         // output the post that we just posted.
915         $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
916         return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
917 }
918
919 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
920 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
921
922 /**
923  * Uploads an image to Friendica.
924  *
925  * @return array
926  * @throws BadRequestException
927  * @throws ForbiddenException
928  * @throws ImagickException
929  * @throws InternalServerErrorException
930  * @throws UnauthorizedException
931  * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
932  */
933 function api_media_upload()
934 {
935         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
936
937         if (empty($_FILES['media'])) {
938                 // Output error
939                 throw new BadRequestException("No media.");
940         }
941
942         $media = wall_upload_post(DI::app(), false);
943         if (!$media) {
944                 // Output error
945                 throw new InternalServerErrorException();
946         }
947
948         $returndata = [];
949         $returndata["media_id"] = $media["id"];
950         $returndata["media_id_string"] = (string)$media["id"];
951         $returndata["size"] = $media["size"];
952         $returndata["image"] = ["w" => $media["width"],
953                                 "h" => $media["height"],
954                                 "image_type" => $media["type"],
955                                 "friendica_preview_url" => $media["preview"]];
956
957         Logger::info('Media uploaded', ['return' => $returndata]);
958
959         return ["media" => $returndata];
960 }
961
962 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
963
964 /**
965  * Updates media meta data (picture descriptions)
966  *
967  * @param string $type Return type (atom, rss, xml, json)
968  *
969  * @return array|string
970  * @throws BadRequestException
971  * @throws ForbiddenException
972  * @throws ImagickException
973  * @throws InternalServerErrorException
974  * @throws TooManyRequestsException
975  * @throws UnauthorizedException
976  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
977  *
978  * @todo Compare the corresponding Twitter function for correct return values
979  */
980 function api_media_metadata_create($type)
981 {
982         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
983         $uid = BaseApi::getCurrentUserID();
984
985         $postdata = Network::postdata();
986
987         if (empty($postdata)) {
988                 throw new BadRequestException("No post data");
989         }
990
991         $data = json_decode($postdata, true);
992         if (empty($data)) {
993                 throw new BadRequestException("Invalid post data");
994         }
995
996         if (empty($data['media_id']) || empty($data['alt_text'])) {
997                 throw new BadRequestException("Missing post data values");
998         }
999
1000         if (empty($data['alt_text']['text'])) {
1001                 throw new BadRequestException("No alt text.");
1002         }
1003
1004         Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1005
1006         $condition = ['id' => $data['media_id'], 'uid' => $uid];
1007         $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1008         if (!DBA::isResult($photo)) {
1009                 throw new BadRequestException("Metadata not found.");
1010         }
1011
1012         DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1013 }
1014
1015 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1016
1017 /**
1018  * Repeats a status.
1019  *
1020  * @param string $type Return type (atom, rss, xml, json)
1021  *
1022  * @return array|string
1023  * @throws BadRequestException
1024  * @throws ForbiddenException
1025  * @throws ImagickException
1026  * @throws InternalServerErrorException
1027  * @throws UnauthorizedException
1028  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1029  */
1030 function api_statuses_repeat($type)
1031 {
1032         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1033         $uid = BaseApi::getCurrentUserID();
1034
1035         // params
1036         $id = intval(DI::args()->getArgv()[3] ?? 0);
1037
1038         if ($id == 0) {
1039                 $id = intval($_REQUEST['id'] ?? 0);
1040         }
1041
1042         // Hotot workaround
1043         if ($id == 0) {
1044                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1045         }
1046
1047         logger::notice('API: api_statuses_repeat: ' . $id);
1048
1049         $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1050         $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1051
1052         if (DBA::isResult($item) && !empty($item['body'])) {
1053                 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1054                         if (!Item::performActivity($id, 'announce', $uid)) {
1055                                 throw new InternalServerErrorException();
1056                         }
1057
1058                         $item_id = $id;
1059                 } else {
1060                         if (strpos($item['body'], "[/share]") !== false) {
1061                                 $pos = strpos($item['body'], "[share");
1062                                 $post = substr($item['body'], $pos);
1063                         } else {
1064                                 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1065
1066                                 if (!empty($item['title'])) {
1067                                         $post .= '[h3]' . $item['title'] . "[/h3]\n";
1068                                 }
1069
1070                                 $post .= $item['body'];
1071                                 $post .= "[/share]";
1072                         }
1073                         $_REQUEST['body'] = $post;
1074                         $_REQUEST['profile_uid'] = $uid;
1075                         $_REQUEST['api_source'] = true;
1076
1077                         if (empty($_REQUEST['source'])) {
1078                                 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
1079                         }
1080
1081                         $item_id = item_post(DI::app());
1082                 }
1083         } else {
1084                 throw new ForbiddenException();
1085         }
1086
1087         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1088
1089         // output the post that we just posted.
1090         $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
1091         return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
1092 }
1093
1094 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1095
1096 /**
1097  * Star/unstar an item.
1098  * param: id : id of the item
1099  *
1100  * @param string $type Return type (atom, rss, xml, json)
1101  *
1102  * @return array|string
1103  * @throws BadRequestException
1104  * @throws ForbiddenException
1105  * @throws ImagickException
1106  * @throws InternalServerErrorException
1107  * @throws UnauthorizedException
1108  * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1109  */
1110 function api_favorites_create_destroy($type)
1111 {
1112         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1113         $uid = BaseApi::getCurrentUserID();
1114
1115         // for versioned api.
1116         /// @TODO We need a better global soluton
1117         $action_argv_id = 2;
1118         if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1119                 $action_argv_id = 3;
1120         }
1121
1122         if (DI::args()->getArgc() <= $action_argv_id) {
1123                 throw new BadRequestException("Invalid request.");
1124         }
1125         $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1126         if (DI::args()->getArgc() == $action_argv_id + 2) {
1127                 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1128         } else {
1129                 $itemid = intval($_REQUEST['id'] ?? 0);
1130         }
1131
1132         $item = Post::selectFirstForUser($uid, [], ['id' => $itemid, 'uid' => $uid]);
1133
1134         if (!DBA::isResult($item)) {
1135                 throw new BadRequestException("Invalid item.");
1136         }
1137
1138         switch ($action) {
1139                 case "create":
1140                         $item['starred'] = 1;
1141                         break;
1142                 case "destroy":
1143                         $item['starred'] = 0;
1144                         break;
1145                 default:
1146                         throw new BadRequestException("Invalid action ".$action);
1147         }
1148
1149         $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1150
1151         if ($r === false) {
1152                 throw new InternalServerErrorException("DB error");
1153         }
1154
1155         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1156
1157         $ret = DI::twitterStatus()->createFromUriId($item['uri-id'], $item['uid'], $include_entities)->toArray();
1158
1159         return DI::apiResponse()->formatData("status", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1160 }
1161
1162 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1163 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1164
1165 /**
1166  * Returns all lists the user subscribes to.
1167  *
1168  * @param string $type Return type (atom, rss, xml, json)
1169  *
1170  * @return array|string
1171  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
1172  */
1173 function api_lists_list($type)
1174 {
1175         $ret = [];
1176         /// @TODO $ret is not filled here?
1177         return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
1178 }
1179
1180 api_register_func('api/lists/list', 'api_lists_list', true);
1181 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
1182
1183 /**
1184  * Returns all groups the user owns.
1185  *
1186  * @param string $type Return type (atom, rss, xml, json)
1187  *
1188  * @return array|string
1189  * @throws BadRequestException
1190  * @throws ForbiddenException
1191  * @throws ImagickException
1192  * @throws InternalServerErrorException
1193  * @throws UnauthorizedException
1194  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
1195  */
1196 function api_lists_ownerships($type)
1197 {
1198         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1199         $uid = BaseApi::getCurrentUserID();
1200
1201         // params
1202         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1203
1204         $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
1205
1206         // loop through all groups
1207         $lists = [];
1208         foreach ($groups as $group) {
1209                 if ($group['visible']) {
1210                         $mode = 'public';
1211                 } else {
1212                         $mode = 'private';
1213                 }
1214                 $lists[] = [
1215                         'name' => $group['name'],
1216                         'id' => intval($group['id']),
1217                         'id_str' => (string) $group['id'],
1218                         'user' => $user_info,
1219                         'mode' => $mode
1220                 ];
1221         }
1222         return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
1223 }
1224
1225 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
1226
1227 /**
1228  * Returns either the friends of the follower list
1229  *
1230  * Considers friends and followers lists to be private and won't return
1231  * anything if any user_id parameter is passed.
1232  *
1233  * @param string $qtype Either "friends" or "followers"
1234  * @return boolean|array
1235  * @throws BadRequestException
1236  * @throws ForbiddenException
1237  * @throws ImagickException
1238  * @throws InternalServerErrorException
1239  * @throws UnauthorizedException
1240  */
1241 function api_statuses_f($qtype)
1242 {
1243         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1244         $uid = BaseApi::getCurrentUserID();
1245
1246         // pagination
1247         $count = $_GET['count'] ?? 20;
1248         $page = $_GET['page'] ?? 1;
1249
1250         $start = max(0, ($page - 1) * $count);
1251
1252         if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
1253                 /* this is to stop Hotot to load friends multiple times
1254                 *  I'm not sure if I'm missing return something or
1255                 *  is a bug in hotot. Workaround, meantime
1256                 */
1257
1258                 /*$ret=Array();
1259                 return array('$users' => $ret);*/
1260                 return false;
1261         }
1262
1263         $sql_extra = '';
1264         if ($qtype == 'friends') {
1265                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
1266         } elseif ($qtype == 'followers') {
1267                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
1268         }
1269
1270         if ($qtype == 'blocks') {
1271                 $sql_filter = 'AND `blocked` AND NOT `pending`';
1272         } elseif ($qtype == 'incoming') {
1273                 $sql_filter = 'AND `pending`';
1274         } else {
1275                 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
1276         }
1277
1278         // @todo This query most likely can be replaced with a Contact::select...
1279         $r = DBA::toArray(DBA::p(
1280                 "SELECT `id`
1281                 FROM `contact`
1282                 WHERE `uid` = ?
1283                 AND NOT `self`
1284                 $sql_filter
1285                 $sql_extra
1286                 ORDER BY `nick`
1287                 LIMIT ?, ?",
1288                 $uid,
1289                 $start,
1290                 $count
1291         ));
1292
1293         $ret = [];
1294         foreach ($r as $cid) {
1295                 $user = DI::twitterUser()->createFromContactId($cid['id'], $uid, false)->toArray();
1296                 // "uid" is only needed for some internal stuff, so remove it from here
1297                 unset($user['uid']);
1298
1299                 if ($user) {
1300                         $ret[] = $user;
1301                 }
1302         }
1303
1304         return ['user' => $ret];
1305 }
1306
1307 /**
1308  * Returns the list of friends of the provided user
1309  *
1310  * @deprecated By Twitter API in favor of friends/list
1311  *
1312  * @param string $type Either "json" or "xml"
1313  * @return boolean|string|array
1314  * @throws BadRequestException
1315  * @throws ForbiddenException
1316  */
1317 function api_statuses_friends($type)
1318 {
1319         $data =  api_statuses_f("friends");
1320         if ($data === false) {
1321                 return false;
1322         }
1323         return DI::apiResponse()->formatData("users", $type, $data);
1324 }
1325
1326 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
1327
1328 /**
1329  * Returns the list of followers of the provided user
1330  *
1331  * @deprecated By Twitter API in favor of friends/list
1332  *
1333  * @param string $type Either "json" or "xml"
1334  * @return boolean|string|array
1335  * @throws BadRequestException
1336  * @throws ForbiddenException
1337  */
1338 function api_statuses_followers($type)
1339 {
1340         $data = api_statuses_f("followers");
1341         if ($data === false) {
1342                 return false;
1343         }
1344         return DI::apiResponse()->formatData("users", $type, $data);
1345 }
1346
1347 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
1348
1349 /**
1350  * Returns the list of blocked users
1351  *
1352  * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
1353  *
1354  * @param string $type Either "json" or "xml"
1355  *
1356  * @return boolean|string|array
1357  * @throws BadRequestException
1358  * @throws ForbiddenException
1359  */
1360 function api_blocks_list($type)
1361 {
1362         $data =  api_statuses_f('blocks');
1363         if ($data === false) {
1364                 return false;
1365         }
1366         return DI::apiResponse()->formatData("users", $type, $data);
1367 }
1368
1369 api_register_func('api/blocks/list', 'api_blocks_list', true);
1370
1371 /**
1372  * Returns the list of pending users IDs
1373  *
1374  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
1375  *
1376  * @param string $type Either "json" or "xml"
1377  *
1378  * @return boolean|string|array
1379  * @throws BadRequestException
1380  * @throws ForbiddenException
1381  */
1382 function api_friendships_incoming($type)
1383 {
1384         $data =  api_statuses_f('incoming');
1385         if ($data === false) {
1386                 return false;
1387         }
1388
1389         $ids = [];
1390         foreach ($data['user'] as $user) {
1391                 $ids[] = $user['id'];
1392         }
1393
1394         return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
1395 }
1396
1397 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
1398
1399 /**
1400  * Sends a new direct message.
1401  *
1402  * @param string $type Return type (atom, rss, xml, json)
1403  *
1404  * @return array|string
1405  * @throws BadRequestException
1406  * @throws ForbiddenException
1407  * @throws ImagickException
1408  * @throws InternalServerErrorException
1409  * @throws NotFoundException
1410  * @throws UnauthorizedException
1411  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
1412  */
1413 function api_direct_messages_new($type)
1414 {
1415         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1416         $uid = BaseApi::getCurrentUserID();
1417
1418         if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
1419                 return;
1420         }
1421
1422         $sender = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1423
1424         $cid = BaseApi::getContactIDForSearchterm($_POST['screen_name'] ?? '', $_POST['user_id'] ?? 0, $uid);
1425         if (empty($cid)) {
1426                 throw new NotFoundException('Recipient not found');
1427         }
1428
1429         $replyto = '';
1430         if (!empty($_REQUEST['replyto'])) {
1431                 $mail    = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
1432                 $replyto = $mail['parent-uri'];
1433                 $sub     = $mail['title'];
1434         } else {
1435                 if (!empty($_REQUEST['title'])) {
1436                         $sub = $_REQUEST['title'];
1437                 } else {
1438                         $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
1439                 }
1440         }
1441
1442         $cdata = Contact::getPublicAndUserContactID($cid, $uid);
1443
1444         $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
1445
1446         if ($id > -1) {
1447                 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
1448                 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid, true)->toArray(), $sender);
1449         } else {
1450                 $ret = ["error" => $id];
1451         }
1452
1453         return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
1454 }
1455
1456 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
1457
1458 /**
1459  * delete a direct_message from mail table through api
1460  *
1461  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1462  * @return string|array
1463  * @throws BadRequestException
1464  * @throws ForbiddenException
1465  * @throws ImagickException
1466  * @throws InternalServerErrorException
1467  * @throws UnauthorizedException
1468  * @see   https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
1469  */
1470 function api_direct_messages_destroy($type)
1471 {
1472         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1473         $uid = BaseApi::getCurrentUserID();
1474
1475         //required
1476         $id = $_REQUEST['id'] ?? 0;
1477         // optional
1478         $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
1479         $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
1480         /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
1481
1482         // error if no id or parenturi specified (for clients posting parent-uri as well)
1483         if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
1484                 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
1485                 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
1486         }
1487
1488         // BadRequestException if no id specified (for clients using Twitter API)
1489         if ($id == 0) {
1490                 throw new BadRequestException('Message id not specified');
1491         }
1492
1493         // add parent-uri to sql command if specified by calling app
1494         $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
1495
1496         // error message if specified id is not in database
1497         if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
1498                 if ($verbose == "true") {
1499                         $answer = ['result' => 'error', 'message' => 'message id not in database'];
1500                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
1501                 }
1502                 /// @todo BadRequestException ok for Twitter API clients?
1503                 throw new BadRequestException('message id not in database');
1504         }
1505
1506         // delete message
1507         $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
1508
1509         if ($verbose == "true") {
1510                 if ($result) {
1511                         // return success
1512                         $answer = ['result' => 'ok', 'message' => 'message deleted'];
1513                         return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
1514                 } else {
1515                         $answer = ['result' => 'error', 'message' => 'unknown error'];
1516                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
1517                 }
1518         }
1519         /// @todo return JSON data like Twitter API not yet implemented
1520 }
1521
1522 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
1523
1524 /**
1525  * Unfollow Contact
1526  *
1527  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1528  * @return string|array
1529  * @throws HTTPException\BadRequestException
1530  * @throws HTTPException\ExpectationFailedException
1531  * @throws HTTPException\ForbiddenException
1532  * @throws HTTPException\InternalServerErrorException
1533  * @throws HTTPException\NotFoundException
1534  * @see   https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
1535  */
1536 function api_friendships_destroy($type)
1537 {
1538         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1539         $uid = BaseApi::getCurrentUserID();
1540
1541         $owner = User::getOwnerDataById($uid);
1542         if (!$owner) {
1543                 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
1544                 throw new HTTPException\NotFoundException('Error Processing Request');
1545         }
1546
1547         $contact_id = $_REQUEST['user_id'] ?? 0;
1548
1549         if (empty($contact_id)) {
1550                 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
1551                 throw new HTTPException\BadRequestException('no user_id specified');
1552         }
1553
1554         // Get Contact by given id
1555         $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
1556
1557         if(!DBA::isResult($contact)) {
1558                 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
1559                 throw new HTTPException\NotFoundException('no contact found to given ID');
1560         }
1561
1562         $url = $contact['url'];
1563
1564         $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
1565                         $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
1566                         Strings::normaliseLink($url), $url];
1567         $contact = DBA::selectFirst('contact', [], $condition);
1568
1569         if (!DBA::isResult($contact)) {
1570                 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
1571                 throw new HTTPException\NotFoundException('Not following Contact');
1572         }
1573
1574         try {
1575                 $result = Contact::terminateFriendship($owner, $contact);
1576
1577                 if ($result === null) {
1578                         Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
1579                         throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
1580                 }
1581
1582                 if ($result === false) {
1583                         throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
1584                 }
1585         } catch (Exception $e) {
1586                 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
1587                 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
1588         }
1589
1590         // "uid" is only needed for some internal stuff, so remove it from here
1591         unset($contact['uid']);
1592
1593         // Set screen_name since Twidere requests it
1594         $contact['screen_name'] = $contact['nick'];
1595
1596         return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
1597 }
1598
1599 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
1600
1601 /**
1602  *
1603  * @param string $type Return type (atom, rss, xml, json)
1604  * @param string $box
1605  * @param string $verbose
1606  *
1607  * @return array|string
1608  * @throws BadRequestException
1609  * @throws ForbiddenException
1610  * @throws ImagickException
1611  * @throws InternalServerErrorException
1612  * @throws UnauthorizedException
1613  */
1614 function api_direct_messages_box($type, $box, $verbose)
1615 {
1616         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1617         $uid = BaseApi::getCurrentUserID();
1618
1619         // params
1620         $count = $_GET['count'] ?? 20;
1621         $page = $_REQUEST['page'] ?? 1;
1622
1623         $since_id = $_REQUEST['since_id'] ?? 0;
1624         $max_id = $_REQUEST['max_id'] ?? 0;
1625
1626         $user_id = $_REQUEST['user_id'] ?? '';
1627         $screen_name = $_REQUEST['screen_name'] ?? '';
1628
1629         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1630
1631         $profile_url = $user_info["url"];
1632
1633         // pagination
1634         $start = max(0, ($page - 1) * $count);
1635
1636         $sql_extra = "";
1637
1638         // filters
1639         if ($box=="sentbox") {
1640                 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
1641         } elseif ($box == "conversation") {
1642                 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '')  . "'";
1643         } elseif ($box == "all") {
1644                 $sql_extra = "true";
1645         } elseif ($box == "inbox") {
1646                 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
1647         }
1648
1649         if ($max_id > 0) {
1650                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
1651         }
1652
1653         if ($user_id != "") {
1654                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
1655         } elseif ($screen_name !="") {
1656                 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
1657         }
1658
1659         $r = DBA::toArray(DBA::p(
1660                 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND $sql_extra AND `mail`.`id` > ? ORDER BY `mail`.`id` DESC LIMIT ?,?",
1661                 $uid,
1662                 $since_id,
1663                 $start,
1664                 $count
1665         ));
1666         if ($verbose == "true" && !DBA::isResult($r)) {
1667                 $answer = ['result' => 'error', 'message' => 'no mails available'];
1668                 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
1669         }
1670
1671         $ret = [];
1672         foreach ($r as $item) {
1673                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
1674                         $recipient = $user_info;
1675                         $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1676                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
1677                         $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
1678                         $sender = $user_info;
1679                 }
1680
1681                 if (isset($recipient) && isset($sender)) {
1682                         $ret[] = api_format_messages($item, $recipient, $sender);
1683                 }
1684         }
1685
1686         return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
1687 }
1688
1689 /**
1690  * Returns the most recent direct messages sent by the user.
1691  *
1692  * @param string $type Return type (atom, rss, xml, json)
1693  *
1694  * @return array|string
1695  * @throws BadRequestException
1696  * @throws ForbiddenException
1697  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
1698  */
1699 function api_direct_messages_sentbox($type)
1700 {
1701         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
1702         return api_direct_messages_box($type, "sentbox", $verbose);
1703 }
1704
1705 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
1706
1707 /**
1708  * Returns the most recent direct messages sent to the user.
1709  *
1710  * @param string $type Return type (atom, rss, xml, json)
1711  *
1712  * @return array|string
1713  * @throws BadRequestException
1714  * @throws ForbiddenException
1715  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
1716  */
1717 function api_direct_messages_inbox($type)
1718 {
1719         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
1720         return api_direct_messages_box($type, "inbox", $verbose);
1721 }
1722
1723 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
1724
1725 /**
1726  *
1727  * @param string $type Return type (atom, rss, xml, json)
1728  *
1729  * @return array|string
1730  * @throws BadRequestException
1731  * @throws ForbiddenException
1732  */
1733 function api_direct_messages_all($type)
1734 {
1735         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
1736         return api_direct_messages_box($type, "all", $verbose);
1737 }
1738
1739 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
1740
1741 /**
1742  *
1743  * @param string $type Return type (atom, rss, xml, json)
1744  *
1745  * @return array|string
1746  * @throws BadRequestException
1747  * @throws ForbiddenException
1748  */
1749 function api_direct_messages_conversation($type)
1750 {
1751         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
1752         return api_direct_messages_box($type, "conversation", $verbose);
1753 }
1754
1755 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
1756
1757 /**
1758  * list all photos of the authenticated user
1759  *
1760  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1761  * @return string|array
1762  * @throws ForbiddenException
1763  * @throws InternalServerErrorException
1764  */
1765 function api_fr_photos_list($type)
1766 {
1767         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1768         $uid = BaseApi::getCurrentUserID();
1769
1770         $r = DBA::toArray(DBA::p(
1771                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
1772                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
1773                 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
1774                 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
1775         ));
1776         $typetoext = [
1777                 'image/jpeg' => 'jpg',
1778                 'image/png' => 'png',
1779                 'image/gif' => 'gif'
1780         ];
1781         $data = ['photo'=>[]];
1782         if (DBA::isResult($r)) {
1783                 foreach ($r as $rr) {
1784                         $photo = [];
1785                         $photo['id'] = $rr['resource-id'];
1786                         $photo['album'] = $rr['album'];
1787                         $photo['filename'] = $rr['filename'];
1788                         $photo['type'] = $rr['type'];
1789                         $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
1790                         $photo['created'] = $rr['created'];
1791                         $photo['edited'] = $rr['edited'];
1792                         $photo['desc'] = $rr['desc'];
1793
1794                         if ($type == "xml") {
1795                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
1796                         } else {
1797                                 $photo['thumb'] = $thumb;
1798                                 $data['photo'][] = $photo;
1799                         }
1800                 }
1801         }
1802         return DI::apiResponse()->formatData("photos", $type, $data);
1803 }
1804
1805 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
1806
1807 /**
1808  * upload a new photo or change an existing photo
1809  *
1810  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1811  * @return string|array
1812  * @throws BadRequestException
1813  * @throws ForbiddenException
1814  * @throws ImagickException
1815  * @throws InternalServerErrorException
1816  * @throws NotFoundException
1817  */
1818 function api_fr_photo_create_update($type)
1819 {
1820         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1821         $uid = BaseApi::getCurrentUserID();
1822
1823         // input params
1824         $photo_id  = $_REQUEST['photo_id']  ?? null;
1825         $desc      = $_REQUEST['desc']      ?? null;
1826         $album     = $_REQUEST['album']     ?? null;
1827         $album_new = $_REQUEST['album_new'] ?? null;
1828         $allow_cid = $_REQUEST['allow_cid'] ?? null;
1829         $deny_cid  = $_REQUEST['deny_cid' ] ?? null;
1830         $allow_gid = $_REQUEST['allow_gid'] ?? null;
1831         $deny_gid  = $_REQUEST['deny_gid' ] ?? null;
1832         $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
1833
1834         // do several checks on input parameters
1835         // we do not allow calls without album string
1836         if ($album == null) {
1837                 throw new BadRequestException("no albumname specified");
1838         }
1839         // if photo_id == null --> we are uploading a new photo
1840         if ($photo_id == null) {
1841                 $mode = "create";
1842
1843                 // error if no media posted in create-mode
1844                 if (empty($_FILES['media'])) {
1845                         // Output error
1846                         throw new BadRequestException("no media data submitted");
1847                 }
1848
1849                 // album_new will be ignored in create-mode
1850                 $album_new = "";
1851         } else {
1852                 $mode = "update";
1853
1854                 // check if photo is existing in databasei
1855                 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
1856                         throw new BadRequestException("photo not available");
1857                 }
1858         }
1859
1860         // checks on acl strings provided by clients
1861         $acl_input_error = false;
1862         $acl_input_error |= check_acl_input($allow_cid, $uid);
1863         $acl_input_error |= check_acl_input($deny_cid, $uid);
1864         $acl_input_error |= check_acl_input($allow_gid, $uid);
1865         $acl_input_error |= check_acl_input($deny_gid, $uid);
1866         if ($acl_input_error) {
1867                 throw new BadRequestException("acl data invalid");
1868         }
1869         // now let's upload the new media in create-mode
1870         if ($mode == "create") {
1871                 $media = $_FILES['media'];
1872                 $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);
1873
1874                 // return success of updating or error message
1875                 if (!is_null($data)) {
1876                         return DI::apiResponse()->formatData("photo_create", $type, $data);
1877                 } else {
1878                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
1879                 }
1880         }
1881
1882         // now let's do the changes in update-mode
1883         if ($mode == "update") {
1884                 $updated_fields = [];
1885
1886                 if (!is_null($desc)) {
1887                         $updated_fields['desc'] = $desc;
1888                 }
1889
1890                 if (!is_null($album_new)) {
1891                         $updated_fields['album'] = $album_new;
1892                 }
1893
1894                 if (!is_null($allow_cid)) {
1895                         $allow_cid = trim($allow_cid);
1896                         $updated_fields['allow_cid'] = $allow_cid;
1897                 }
1898
1899                 if (!is_null($deny_cid)) {
1900                         $deny_cid = trim($deny_cid);
1901                         $updated_fields['deny_cid'] = $deny_cid;
1902                 }
1903
1904                 if (!is_null($allow_gid)) {
1905                         $allow_gid = trim($allow_gid);
1906                         $updated_fields['allow_gid'] = $allow_gid;
1907                 }
1908
1909                 if (!is_null($deny_gid)) {
1910                         $deny_gid = trim($deny_gid);
1911                         $updated_fields['deny_gid'] = $deny_gid;
1912                 }
1913
1914                 $result = false;
1915                 if (count($updated_fields) > 0) {
1916                         $nothingtodo = false;
1917                         $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
1918                 } else {
1919                         $nothingtodo = true;
1920                 }
1921
1922                 if (!empty($_FILES['media'])) {
1923                         $nothingtodo = false;
1924                         $media = $_FILES['media'];
1925                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
1926                         if (!is_null($data)) {
1927                                 return DI::apiResponse()->formatData("photo_update", $type, $data);
1928                         }
1929                 }
1930
1931                 // return success of updating or error message
1932                 if ($result) {
1933                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
1934                         return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1935                 } else {
1936                         if ($nothingtodo) {
1937                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
1938                                 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
1939                         }
1940                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
1941                 }
1942         }
1943         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
1944 }
1945
1946 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
1947 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
1948
1949 /**
1950  * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
1951  *
1952  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1953  * @return string|array
1954  * @throws BadRequestException
1955  * @throws ForbiddenException
1956  * @throws InternalServerErrorException
1957  * @throws NotFoundException
1958  */
1959 function api_fr_photo_detail($type)
1960 {
1961         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1962         $uid = BaseApi::getCurrentUserID();
1963
1964         if (empty($_REQUEST['photo_id'])) {
1965                 throw new BadRequestException("No photo id.");
1966         }
1967
1968         $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
1969         $photo_id = $_REQUEST['photo_id'];
1970
1971         // prepare json/xml output with data from database for the requested photo
1972         $data = prepare_photo_data($type, $scale, $photo_id, $uid);
1973
1974         return DI::apiResponse()->formatData("photo_detail", $type, $data);
1975 }
1976
1977 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
1978
1979 /**
1980  * updates the profile image for the user (either a specified profile or the default profile)
1981  *
1982  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1983  *
1984  * @return string|array
1985  * @throws BadRequestException
1986  * @throws ForbiddenException
1987  * @throws ImagickException
1988  * @throws InternalServerErrorException
1989  * @throws NotFoundException
1990  * @see   https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
1991  */
1992 function api_account_update_profile_image($type)
1993 {
1994         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1995         $uid = BaseApi::getCurrentUserID();
1996
1997         // input params
1998         $profile_id = $_REQUEST['profile_id'] ?? 0;
1999
2000         // error if image data is missing
2001         if (empty($_FILES['image'])) {
2002                 throw new BadRequestException("no media data submitted");
2003         }
2004
2005         // check if specified profile id is valid
2006         if ($profile_id != 0) {
2007                 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
2008                 // error message if specified profile id is not in database
2009                 if (!DBA::isResult($profile)) {
2010                         throw new BadRequestException("profile_id not available");
2011                 }
2012                 $is_default_profile = $profile['is-default'];
2013         } else {
2014                 $is_default_profile = 1;
2015         }
2016
2017         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
2018         $media = null;
2019         if (!empty($_FILES['image'])) {
2020                 $media = $_FILES['image'];
2021         } elseif (!empty($_FILES['media'])) {
2022                 $media = $_FILES['media'];
2023         }
2024         // save new profile image
2025         $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
2026
2027         // get filetype
2028         if (is_array($media['type'])) {
2029                 $filetype = $media['type'][0];
2030         } else {
2031                 $filetype = $media['type'];
2032         }
2033         if ($filetype == "image/jpeg") {
2034                 $fileext = "jpg";
2035         } elseif ($filetype == "image/png") {
2036                 $fileext = "png";
2037         } else {
2038                 throw new InternalServerErrorException('Unsupported filetype');
2039         }
2040
2041         // change specified profile or all profiles to the new resource-id
2042         if ($is_default_profile) {
2043                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
2044                 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
2045         } else {
2046                 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
2047                         'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
2048                 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
2049         }
2050
2051         Contact::updateSelfFromUserID($uid, true);
2052
2053         // Update global directory in background
2054         Profile::publishUpdate($uid);
2055
2056         // output for client
2057         if ($data) {
2058                 $skip_status = $_REQUEST['skip_status'] ?? false;
2059
2060                 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
2061
2062                 // "verified" isn't used here in the standard
2063                 unset($user_info["verified"]);
2064
2065                 // "uid" is only needed for some internal stuff, so remove it from here
2066                 unset($user_info['uid']);
2067
2068                 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
2069         } else {
2070                 // SaveMediaToDatabase failed for some reason
2071                 throw new InternalServerErrorException("image upload failed");
2072         }
2073 }
2074
2075 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
2076
2077 /**
2078  * Return all or a specified group of the user with the containing contacts.
2079  *
2080  * @param string $type Return type (atom, rss, xml, json)
2081  *
2082  * @return array|string
2083  * @throws BadRequestException
2084  * @throws ForbiddenException
2085  * @throws ImagickException
2086  * @throws InternalServerErrorException
2087  * @throws UnauthorizedException
2088  */
2089 function api_friendica_group_show($type)
2090 {
2091         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2092         $uid = BaseApi::getCurrentUserID();
2093
2094         // params
2095         $gid = $_REQUEST['gid'] ?? 0;
2096
2097         // get data of the specified group id or all groups if not specified
2098         if ($gid != 0) {
2099                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
2100
2101                 // error message if specified gid is not in database
2102                 if (!DBA::isResult($groups)) {
2103                         throw new BadRequestException("gid not available");
2104                 }
2105         } else {
2106                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
2107         }
2108
2109         // loop through all groups and retrieve all members for adding data in the user array
2110         $grps = [];
2111         foreach ($groups as $rr) {
2112                 $members = Contact\Group::getById($rr['id']);
2113                 $users = [];
2114
2115                 if ($type == "xml") {
2116                         $user_element = "users";
2117                         $k = 0;
2118                         foreach ($members as $member) {
2119                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
2120                                 $users[$k++.":user"] = $user;
2121                         }
2122                 } else {
2123                         $user_element = "user";
2124                         foreach ($members as $member) {
2125                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
2126                                 $users[] = $user;
2127                         }
2128                 }
2129                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
2130         }
2131         return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
2132 }
2133
2134 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
2135
2136 /**
2137  * Delete a group.
2138  *
2139  * @param string $type Return type (atom, rss, xml, json)
2140  *
2141  * @return array|string
2142  * @throws BadRequestException
2143  * @throws ForbiddenException
2144  * @throws ImagickException
2145  * @throws InternalServerErrorException
2146  * @throws UnauthorizedException
2147  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
2148  */
2149 function api_lists_destroy($type)
2150 {
2151         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2152         $uid = BaseApi::getCurrentUserID();
2153
2154         // params
2155         $gid = $_REQUEST['list_id'] ?? 0;
2156
2157         // error if no gid specified
2158         if ($gid == 0) {
2159                 throw new BadRequestException('gid not specified');
2160         }
2161
2162         // get data of the specified group id
2163         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
2164         // error message if specified gid is not in database
2165         if (!$group) {
2166                 throw new BadRequestException('gid not available');
2167         }
2168
2169         if (Group::remove($gid)) {
2170                 $list = [
2171                         'name' => $group['name'],
2172                         'id' => intval($gid),
2173                         'id_str' => (string) $gid,
2174                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
2175                 ];
2176
2177                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
2178         }
2179 }
2180
2181 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
2182
2183 /**
2184  * Create the specified group with the posted array of contacts.
2185  *
2186  * @param string $type Return type (atom, rss, xml, json)
2187  *
2188  * @return array|string
2189  * @throws BadRequestException
2190  * @throws ForbiddenException
2191  * @throws ImagickException
2192  * @throws InternalServerErrorException
2193  * @throws UnauthorizedException
2194  */
2195 function api_friendica_group_create($type)
2196 {
2197         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2198         $uid = BaseApi::getCurrentUserID();
2199
2200         // params
2201         $name = $_REQUEST['name'] ?? '';
2202         $json = json_decode($_POST['json'], true);
2203         $users = $json['user'];
2204
2205         $success = group_create($name, $uid, $users);
2206
2207         return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
2208 }
2209
2210 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
2211
2212 /**
2213  * Create a new group.
2214  *
2215  * @param string $type Return type (atom, rss, xml, json)
2216  *
2217  * @return array|string
2218  * @throws BadRequestException
2219  * @throws ForbiddenException
2220  * @throws ImagickException
2221  * @throws InternalServerErrorException
2222  * @throws UnauthorizedException
2223  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
2224  */
2225 function api_lists_create($type)
2226 {
2227         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2228         $uid = BaseApi::getCurrentUserID();
2229
2230         // params
2231         $name = $_REQUEST['name'] ?? '';
2232
2233         $success = group_create($name, $uid);
2234         if ($success['success']) {
2235                 $grp = [
2236                         'name' => $success['name'],
2237                         'id' => intval($success['gid']),
2238                         'id_str' => (string) $success['gid'],
2239                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
2240                 ];
2241
2242                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
2243         }
2244 }
2245
2246 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
2247
2248 /**
2249  * Update the specified group with the posted array of contacts.
2250  *
2251  * @param string $type Return type (atom, rss, xml, json)
2252  *
2253  * @return array|string
2254  * @throws BadRequestException
2255  * @throws ForbiddenException
2256  * @throws ImagickException
2257  * @throws InternalServerErrorException
2258  * @throws UnauthorizedException
2259  */
2260 function api_friendica_group_update($type)
2261 {
2262         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2263         $uid = BaseApi::getCurrentUserID();
2264
2265         // params
2266         $gid = $_REQUEST['gid'] ?? 0;
2267         $name = $_REQUEST['name'] ?? '';
2268         $json = json_decode($_POST['json'], true);
2269         $users = $json['user'];
2270
2271         // error if no name specified
2272         if ($name == "") {
2273                 throw new BadRequestException('group name not specified');
2274         }
2275
2276         // error if no gid specified
2277         if ($gid == "") {
2278                 throw new BadRequestException('gid not specified');
2279         }
2280
2281         // remove members
2282         $members = Contact\Group::getById($gid);
2283         foreach ($members as $member) {
2284                 $cid = $member['id'];
2285                 foreach ($users as $user) {
2286                         $found = ($user['cid'] == $cid ? true : false);
2287                 }
2288                 if (!isset($found) || !$found) {
2289                         $gid = Group::getIdByName($uid, $name);
2290                         Group::removeMember($gid, $cid);
2291                 }
2292         }
2293
2294         // add members
2295         $erroraddinguser = false;
2296         $errorusers = [];
2297         foreach ($users as $user) {
2298                 $cid = $user['cid'];
2299
2300                 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
2301                         Group::addMember($gid, $cid);
2302                 } else {
2303                         $erroraddinguser = true;
2304                         $errorusers[] = $cid;
2305                 }
2306         }
2307
2308         // return success message incl. missing users in array
2309         $status = ($erroraddinguser ? "missing user" : "ok");
2310         $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
2311         return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
2312 }
2313
2314 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
2315
2316 /**
2317  * Update information about a group.
2318  *
2319  * @param string $type Return type (atom, rss, xml, json)
2320  *
2321  * @return array|string
2322  * @throws BadRequestException
2323  * @throws ForbiddenException
2324  * @throws ImagickException
2325  * @throws InternalServerErrorException
2326  * @throws UnauthorizedException
2327  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
2328  */
2329 function api_lists_update($type)
2330 {
2331         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2332         $uid = BaseApi::getCurrentUserID();
2333
2334         // params
2335         $gid = $_REQUEST['list_id'] ?? 0;
2336         $name = $_REQUEST['name'] ?? '';
2337
2338         // error if no gid specified
2339         if ($gid == 0) {
2340                 throw new BadRequestException('gid not specified');
2341         }
2342
2343         // get data of the specified group id
2344         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
2345         // error message if specified gid is not in database
2346         if (!$group) {
2347                 throw new BadRequestException('gid not available');
2348         }
2349
2350         if (Group::update($gid, $name)) {
2351                 $list = [
2352                         'name' => $name,
2353                         'id' => intval($gid),
2354                         'id_str' => (string) $gid,
2355                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
2356                 ];
2357
2358                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
2359         }
2360 }
2361
2362 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
2363
2364 /**
2365  * search for direct_messages containing a searchstring through api
2366  *
2367  * @param string $type      Known types are 'atom', 'rss', 'xml' and 'json'
2368  * @param string $box
2369  * @return string|array (success: success=true if found and search_result contains found messages,
2370  *                          success=false if nothing was found, search_result='nothing found',
2371  *                          error: result=error with error message)
2372  * @throws BadRequestException
2373  * @throws ForbiddenException
2374  * @throws ImagickException
2375  * @throws InternalServerErrorException
2376  * @throws UnauthorizedException
2377  */
2378 function api_friendica_direct_messages_search($type, $box = "")
2379 {
2380         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2381         $uid = BaseApi::getCurrentUserID();
2382
2383         // params
2384         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2385         $searchstring = $_REQUEST['searchstring'] ?? '';
2386
2387         // error if no searchstring specified
2388         if ($searchstring == "") {
2389                 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
2390                 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
2391         }
2392
2393         // get data for the specified searchstring
2394         $r = DBA::toArray(DBA::p(
2395                 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND `body` LIKE ? ORDER BY `mail`.`id` DESC",
2396                 $uid,
2397                 '%'.$searchstring.'%'
2398         ));
2399
2400         $profile_url = $user_info["url"];
2401
2402         // message if nothing was found
2403         if (!DBA::isResult($r)) {
2404                 $success = ['success' => false, 'search_results' => 'problem with query'];
2405         } elseif (count($r) == 0) {
2406                 $success = ['success' => false, 'search_results' => 'nothing found'];
2407         } else {
2408                 $ret = [];
2409                 foreach ($r as $item) {
2410                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
2411                                 $recipient = $user_info;
2412                                 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2413                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
2414                                 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2415                                 $sender = $user_info;
2416                         }
2417
2418                         if (isset($recipient) && isset($sender)) {
2419                                 $ret[] = api_format_messages($item, $recipient, $sender);
2420                         }
2421                 }
2422                 $success = ['success' => true, 'search_results' => $ret];
2423         }
2424
2425         return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
2426 }
2427
2428 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);