]> git.mxchange.org Git - friendica.git/blob - include/api.php
Many API calls 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  * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1019  * The author's most recent status will be returned inline.
1020  *
1021  * @param string $type Return type (atom, rss, xml, json)
1022  * @return array|string
1023  * @throws BadRequestException
1024  * @throws ImagickException
1025  * @throws InternalServerErrorException
1026  * @throws UnauthorizedException
1027  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1028  */
1029 function api_users_show($type)
1030 {
1031         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1032         $uid = BaseApi::getCurrentUserID();
1033
1034         $user_info = DI::twitterUser()->createFromUserId($uid, false)->toArray();
1035
1036         // "uid" is only needed for some internal stuff, so remove it from here
1037         unset($user_info['uid']);
1038
1039         return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
1040 }
1041
1042 api_register_func('api/users/show', 'api_users_show');
1043 api_register_func('api/externalprofile/show', 'api_users_show');
1044
1045 /**
1046  * Search a public user account.
1047  *
1048  * @param string $type Return type (atom, rss, xml, json)
1049  *
1050  * @return array|string
1051  * @throws BadRequestException
1052  * @throws ImagickException
1053  * @throws InternalServerErrorException
1054  * @throws UnauthorizedException
1055  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1056  */
1057 function api_users_search($type)
1058 {
1059         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1060         $uid = BaseApi::getCurrentUserID();
1061
1062         $userlist = [];
1063
1064         if (!empty($_GET['q'])) {
1065                 $contacts = Contact::selectToArray(
1066                         ['id'],
1067                         [
1068                                 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1069                                 $_GET['q'],
1070                                 $_GET['q'],
1071                                 $_GET['q'],
1072                                 $_GET['q'],
1073                         ]
1074                 );
1075
1076                 if (DBA::isResult($contacts)) {
1077                         $k = 0;
1078                         foreach ($contacts as $contact) {
1079                                 $user_info = DI::twitterUser()->createFromContactId($contact['id'], $uid, false)->toArray();
1080
1081                                 if ($type == 'xml') {
1082                                         $userlist[$k++ . ':user'] = $user_info;
1083                                 } else {
1084                                         $userlist[] = $user_info;
1085                                 }
1086                         }
1087                         $userlist = ['users' => $userlist];
1088                 } else {
1089                         throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1090                 }
1091         } else {
1092                 throw new BadRequestException('No search term specified.');
1093         }
1094
1095         return DI::apiResponse()->formatData('users', $type, $userlist);
1096 }
1097
1098 api_register_func('api/users/search', 'api_users_search');
1099
1100 /**
1101  * Return user objects
1102  *
1103  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1104  *
1105  * @param string $type Return format: json or xml
1106  *
1107  * @return array|string
1108  * @throws BadRequestException
1109  * @throws ImagickException
1110  * @throws InternalServerErrorException
1111  * @throws NotFoundException if the results are empty.
1112  * @throws UnauthorizedException
1113  */
1114 function api_users_lookup($type)
1115 {
1116         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1117         $uid = BaseApi::getCurrentUserID();
1118
1119         $users = [];
1120
1121         if (!empty($_REQUEST['user_id'])) {
1122                 foreach (explode(',', $_REQUEST['user_id']) as $cid) {
1123                         if (!empty($cid) && is_numeric($cid)) {
1124                                 $users[] = DI::twitterUser()->createFromContactId((int)$cid, $uid, false)->toArray();
1125                         }
1126                 }
1127         }
1128
1129         if (empty($users)) {
1130                 throw new NotFoundException;
1131         }
1132
1133         return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
1134 }
1135
1136 api_register_func('api/users/lookup', 'api_users_lookup', true);
1137
1138 /**
1139  * Returns statuses that match a specified query.
1140  *
1141  * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1142  *
1143  * @param string $type Return format: json, xml, atom, rss
1144  *
1145  * @return array|string
1146  * @throws BadRequestException if the "q" parameter is missing.
1147  * @throws ForbiddenException
1148  * @throws ImagickException
1149  * @throws InternalServerErrorException
1150  * @throws UnauthorizedException
1151  */
1152 function api_search($type)
1153 {
1154         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1155         $uid = BaseApi::getCurrentUserID();
1156
1157         if (empty($_REQUEST['q'])) {
1158                 throw new BadRequestException('q parameter is required.');
1159         }
1160
1161         $searchTerm = trim(rawurldecode($_REQUEST['q']));
1162
1163         $data = [];
1164         $data['status'] = [];
1165         $count = 15;
1166         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1167         if (!empty($_REQUEST['rpp'])) {
1168                 $count = $_REQUEST['rpp'];
1169         } elseif (!empty($_REQUEST['count'])) {
1170                 $count = $_REQUEST['count'];
1171         }
1172
1173         $since_id = $_REQUEST['since_id'] ?? 0;
1174         $max_id = $_REQUEST['max_id'] ?? 0;
1175         $page = $_REQUEST['page'] ?? 1;
1176
1177         $start = max(0, ($page - 1) * $count);
1178
1179         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1180         if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1181                 $searchTerm = $matches[1];
1182                 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, $uid];
1183                 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1184                 $uriids = [];
1185                 while ($tag = DBA::fetch($tags)) {
1186                         $uriids[] = $tag['uri-id'];
1187                 }
1188                 DBA::close($tags);
1189
1190                 if (empty($uriids)) {
1191                         return DI::apiResponse()->formatData('statuses', $type, $data);
1192                 }
1193
1194                 $condition = ['uri-id' => $uriids];
1195                 if ($exclude_replies) {
1196                         $condition['gravity'] = GRAVITY_PARENT;
1197                 }
1198
1199                 $params['group_by'] = ['uri-id'];
1200         } else {
1201                 $condition = ["`id` > ?
1202                         " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1203                         AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1204                         AND `body` LIKE CONCAT('%',?,'%')",
1205                         $since_id, $uid, $_REQUEST['q']];
1206                 if ($max_id > 0) {
1207                         $condition[0] .= ' AND `id` <= ?';
1208                         $condition[] = $max_id;
1209                 }
1210         }
1211
1212         $statuses = [];
1213
1214         if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1215                 $id = Item::fetchByLink($searchTerm, $uid);
1216                 if (!$id) {
1217                         // Public post
1218                         $id = Item::fetchByLink($searchTerm);
1219                 }
1220
1221                 if (!empty($id)) {
1222                         $statuses = Post::select([], ['id' => $id]);
1223                 }
1224         }
1225
1226         $statuses = $statuses ?: Post::selectForUser($uid, [], $condition, $params);
1227
1228         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1229
1230         $ret = [];
1231         while ($status = DBA::fetch($statuses)) {
1232                 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1233         }
1234         DBA::close($statuses);
1235
1236         $data['status'] = $ret;
1237
1238         return DI::apiResponse()->formatData('statuses', $type, $data);
1239 }
1240
1241 api_register_func('api/search/tweets', 'api_search', true);
1242 api_register_func('api/search', 'api_search', true);
1243
1244 /**
1245  * Returns a single status.
1246  *
1247  * @param string $type Return type (atom, rss, xml, json)
1248  *
1249  * @return array|string
1250  * @throws BadRequestException
1251  * @throws ForbiddenException
1252  * @throws ImagickException
1253  * @throws InternalServerErrorException
1254  * @throws UnauthorizedException
1255  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1256  */
1257 function api_statuses_show($type)
1258 {
1259         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1260         $uid = BaseApi::getCurrentUserID();
1261
1262         // params
1263         $id = intval(DI::args()->getArgv()[3] ?? 0);
1264
1265         if ($id == 0) {
1266                 $id = intval($_REQUEST['id'] ?? 0);
1267         }
1268
1269         // Hotot workaround
1270         if ($id == 0) {
1271                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1272         }
1273
1274         logger::notice('API: api_statuses_show: ' . $id);
1275
1276         $conversation = !empty($_REQUEST['conversation']);
1277
1278         // try to fetch the item for the local user - or the public item, if there is no local one
1279         $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1280         if (!DBA::isResult($uri_item)) {
1281                 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1282         }
1283
1284         $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1285         if (!DBA::isResult($item)) {
1286                 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1287         }
1288
1289         $id = $item['id'];
1290
1291         if ($conversation) {
1292                 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1293                 $params = ['order' => ['id' => true]];
1294         } else {
1295                 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1296                 $params = [];
1297         }
1298
1299         $statuses = Post::selectForUser($uid, [], $condition, $params);
1300
1301         /// @TODO How about copying this to above methods which don't check $r ?
1302         if (!DBA::isResult($statuses)) {
1303                 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1304         }
1305
1306         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1307
1308         $ret = [];
1309         while ($status = DBA::fetch($statuses)) {
1310                 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1311         }
1312         DBA::close($statuses);
1313
1314         if ($conversation) {
1315                 $data = ['status' => $ret];
1316                 return DI::apiResponse()->formatData("statuses", $type, $data);
1317         } else {
1318                 $data = ['status' => $ret[0]];
1319                 return DI::apiResponse()->formatData("status", $type, $data);
1320         }
1321 }
1322
1323 api_register_func('api/statuses/show', 'api_statuses_show', true);
1324
1325 /**
1326  *
1327  * @param string $type Return type (atom, rss, xml, json)
1328  *
1329  * @return array|string
1330  * @throws BadRequestException
1331  * @throws ForbiddenException
1332  * @throws ImagickException
1333  * @throws InternalServerErrorException
1334  * @throws UnauthorizedException
1335  * @todo nothing to say?
1336  */
1337 function api_conversation_show($type)
1338 {
1339         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1340         $uid = BaseApi::getCurrentUserID();
1341
1342         // params
1343         $id       = intval(DI::args()->getArgv()[3]           ?? 0);
1344         $since_id = intval($_REQUEST['since_id'] ?? 0);
1345         $max_id   = intval($_REQUEST['max_id']   ?? 0);
1346         $count    = intval($_REQUEST['count']    ?? 20);
1347         $page     = intval($_REQUEST['page']     ?? 1);
1348
1349         $start = max(0, ($page - 1) * $count);
1350
1351         if ($id == 0) {
1352                 $id = intval($_REQUEST['id'] ?? 0);
1353         }
1354
1355         // Hotot workaround
1356         if ($id == 0) {
1357                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1358         }
1359
1360         Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1361
1362         // try to fetch the item for the local user - or the public item, if there is no local one
1363         $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1364         if (!DBA::isResult($item)) {
1365                 throw new BadRequestException("There is no status with the id $id.");
1366         }
1367
1368         $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1369         if (!DBA::isResult($parent)) {
1370                 throw new BadRequestException("There is no status with this id.");
1371         }
1372
1373         $id = $parent['id'];
1374
1375         $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1376                 $id, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1377
1378         if ($max_id > 0) {
1379                 $condition[0] .= " AND `id` <= ?";
1380                 $condition[] = $max_id;
1381         }
1382
1383         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1384         $statuses = Post::selectForUser($uid, [], $condition, $params);
1385
1386         if (!DBA::isResult($statuses)) {
1387                 throw new BadRequestException("There is no status with id $id.");
1388         }
1389
1390         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1391
1392         $ret = [];
1393         while ($status = DBA::fetch($statuses)) {
1394                 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1395         }
1396         DBA::close($statuses);
1397
1398         $data = ['status' => $ret];
1399         return DI::apiResponse()->formatData("statuses", $type, $data);
1400 }
1401
1402 api_register_func('api/conversation/show', 'api_conversation_show', true);
1403 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1404
1405 /**
1406  * Repeats a status.
1407  *
1408  * @param string $type Return type (atom, rss, xml, json)
1409  *
1410  * @return array|string
1411  * @throws BadRequestException
1412  * @throws ForbiddenException
1413  * @throws ImagickException
1414  * @throws InternalServerErrorException
1415  * @throws UnauthorizedException
1416  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1417  */
1418 function api_statuses_repeat($type)
1419 {
1420         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1421         $uid = BaseApi::getCurrentUserID();
1422
1423         // params
1424         $id = intval(DI::args()->getArgv()[3] ?? 0);
1425
1426         if ($id == 0) {
1427                 $id = intval($_REQUEST['id'] ?? 0);
1428         }
1429
1430         // Hotot workaround
1431         if ($id == 0) {
1432                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1433         }
1434
1435         logger::notice('API: api_statuses_repeat: ' . $id);
1436
1437         $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1438         $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1439
1440         if (DBA::isResult($item) && !empty($item['body'])) {
1441                 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1442                         if (!Item::performActivity($id, 'announce', $uid)) {
1443                                 throw new InternalServerErrorException();
1444                         }
1445
1446                         $item_id = $id;
1447                 } else {
1448                         if (strpos($item['body'], "[/share]") !== false) {
1449                                 $pos = strpos($item['body'], "[share");
1450                                 $post = substr($item['body'], $pos);
1451                         } else {
1452                                 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1453
1454                                 if (!empty($item['title'])) {
1455                                         $post .= '[h3]' . $item['title'] . "[/h3]\n";
1456                                 }
1457
1458                                 $post .= $item['body'];
1459                                 $post .= "[/share]";
1460                         }
1461                         $_REQUEST['body'] = $post;
1462                         $_REQUEST['profile_uid'] = $uid;
1463                         $_REQUEST['api_source'] = true;
1464
1465                         if (empty($_REQUEST['source'])) {
1466                                 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
1467                         }
1468
1469                         $item_id = item_post(DI::app());
1470                 }
1471         } else {
1472                 throw new ForbiddenException();
1473         }
1474
1475         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1476
1477         // output the post that we just posted.
1478         $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
1479         return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
1480 }
1481
1482 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1483
1484 /**
1485  * Destroys a specific status.
1486  *
1487  * @param string $type Return type (atom, rss, xml, json)
1488  *
1489  * @return array|string
1490  * @throws BadRequestException
1491  * @throws ForbiddenException
1492  * @throws ImagickException
1493  * @throws InternalServerErrorException
1494  * @throws UnauthorizedException
1495  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1496  */
1497 function api_statuses_destroy($type)
1498 {
1499         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1500         $uid = BaseApi::getCurrentUserID();
1501
1502         // params
1503         $id = intval(DI::args()->getArgv()[3] ?? 0);
1504
1505         if ($id == 0) {
1506                 $id = intval($_REQUEST['id'] ?? 0);
1507         }
1508
1509         // Hotot workaround
1510         if ($id == 0) {
1511                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1512         }
1513
1514         logger::notice('API: api_statuses_destroy: ' . $id);
1515
1516         $ret = api_statuses_show($type);
1517
1518         Item::deleteForUser(['id' => $id], $uid);
1519
1520         return $ret;
1521 }
1522
1523 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1524
1525 /**
1526  * Star/unstar an item.
1527  * param: id : id of the item
1528  *
1529  * @param string $type Return type (atom, rss, xml, json)
1530  *
1531  * @return array|string
1532  * @throws BadRequestException
1533  * @throws ForbiddenException
1534  * @throws ImagickException
1535  * @throws InternalServerErrorException
1536  * @throws UnauthorizedException
1537  * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1538  */
1539 function api_favorites_create_destroy($type)
1540 {
1541         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1542         $uid = BaseApi::getCurrentUserID();
1543
1544         // for versioned api.
1545         /// @TODO We need a better global soluton
1546         $action_argv_id = 2;
1547         if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1548                 $action_argv_id = 3;
1549         }
1550
1551         if (DI::args()->getArgc() <= $action_argv_id) {
1552                 throw new BadRequestException("Invalid request.");
1553         }
1554         $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1555         if (DI::args()->getArgc() == $action_argv_id + 2) {
1556                 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1557         } else {
1558                 $itemid = intval($_REQUEST['id'] ?? 0);
1559         }
1560
1561         $item = Post::selectFirstForUser($uid, [], ['id' => $itemid, 'uid' => $uid]);
1562
1563         if (!DBA::isResult($item)) {
1564                 throw new BadRequestException("Invalid item.");
1565         }
1566
1567         switch ($action) {
1568                 case "create":
1569                         $item['starred'] = 1;
1570                         break;
1571                 case "destroy":
1572                         $item['starred'] = 0;
1573                         break;
1574                 default:
1575                         throw new BadRequestException("Invalid action ".$action);
1576         }
1577
1578         $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1579
1580         if ($r === false) {
1581                 throw new InternalServerErrorException("DB error");
1582         }
1583
1584         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1585
1586         $ret = DI::twitterStatus()->createFromUriId($item['uri-id'], $item['uid'], $include_entities)->toArray();
1587
1588         return DI::apiResponse()->formatData("status", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1589 }
1590
1591 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1592 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1593
1594 /**
1595  * Returns all lists the user subscribes to.
1596  *
1597  * @param string $type Return type (atom, rss, xml, json)
1598  *
1599  * @return array|string
1600  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
1601  */
1602 function api_lists_list($type)
1603 {
1604         $ret = [];
1605         /// @TODO $ret is not filled here?
1606         return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
1607 }
1608
1609 api_register_func('api/lists/list', 'api_lists_list', true);
1610 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
1611
1612 /**
1613  * Returns all groups the user owns.
1614  *
1615  * @param string $type Return type (atom, rss, xml, json)
1616  *
1617  * @return array|string
1618  * @throws BadRequestException
1619  * @throws ForbiddenException
1620  * @throws ImagickException
1621  * @throws InternalServerErrorException
1622  * @throws UnauthorizedException
1623  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
1624  */
1625 function api_lists_ownerships($type)
1626 {
1627         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1628         $uid = BaseApi::getCurrentUserID();
1629
1630         // params
1631         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1632
1633         $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
1634
1635         // loop through all groups
1636         $lists = [];
1637         foreach ($groups as $group) {
1638                 if ($group['visible']) {
1639                         $mode = 'public';
1640                 } else {
1641                         $mode = 'private';
1642                 }
1643                 $lists[] = [
1644                         'name' => $group['name'],
1645                         'id' => intval($group['id']),
1646                         'id_str' => (string) $group['id'],
1647                         'user' => $user_info,
1648                         'mode' => $mode
1649                 ];
1650         }
1651         return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
1652 }
1653
1654 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
1655
1656 /**
1657  * Returns recent statuses from users in the specified group.
1658  *
1659  * @param string $type Return type (atom, rss, xml, json)
1660  *
1661  * @return array|string
1662  * @throws BadRequestException
1663  * @throws ForbiddenException
1664  * @throws ImagickException
1665  * @throws InternalServerErrorException
1666  * @throws UnauthorizedException
1667  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
1668  */
1669 function api_lists_statuses($type)
1670 {
1671         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1672         $uid = BaseApi::getCurrentUserID();
1673
1674         if (empty($_REQUEST['list_id'])) {
1675                 throw new BadRequestException('list_id not specified');
1676         }
1677
1678         // params
1679         $count = $_REQUEST['count'] ?? 20;
1680         $page = $_REQUEST['page'] ?? 1;
1681         $since_id = $_REQUEST['since_id'] ?? 0;
1682         $max_id = $_REQUEST['max_id'] ?? 0;
1683         $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1684         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1685
1686         $start = max(0, ($page - 1) * $count);
1687
1688         $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
1689         $gids = array_column($groups, 'contact-id');
1690         $condition = ['uid' => $uid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
1691         $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
1692
1693         if ($max_id > 0) {
1694                 $condition[0] .= " AND `id` <= ?";
1695                 $condition[] = $max_id;
1696         }
1697         if ($exclude_replies > 0) {
1698                 $condition[0] .= ' AND `gravity` = ?';
1699                 $condition[] = GRAVITY_PARENT;
1700         }
1701         if ($conversation_id > 0) {
1702                 $condition[0] .= " AND `parent` = ?";
1703                 $condition[] = $conversation_id;
1704         }
1705
1706         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1707         $statuses = Post::selectForUser($uid, [], $condition, $params);
1708
1709         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1710
1711         $items = [];
1712         while ($status = DBA::fetch($statuses)) {
1713                 $items[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1714         }
1715         DBA::close($statuses);
1716
1717         return DI::apiResponse()->formatData("statuses", $type, ['status' => $items], Contact::getPublicIdByUserId($uid));
1718 }
1719
1720 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
1721
1722 /**
1723  * Returns either the friends of the follower list
1724  *
1725  * Considers friends and followers lists to be private and won't return
1726  * anything if any user_id parameter is passed.
1727  *
1728  * @param string $qtype Either "friends" or "followers"
1729  * @return boolean|array
1730  * @throws BadRequestException
1731  * @throws ForbiddenException
1732  * @throws ImagickException
1733  * @throws InternalServerErrorException
1734  * @throws UnauthorizedException
1735  */
1736 function api_statuses_f($qtype)
1737 {
1738         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1739         $uid = BaseApi::getCurrentUserID();
1740
1741         // pagination
1742         $count = $_GET['count'] ?? 20;
1743         $page = $_GET['page'] ?? 1;
1744
1745         $start = max(0, ($page - 1) * $count);
1746
1747         if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
1748                 /* this is to stop Hotot to load friends multiple times
1749                 *  I'm not sure if I'm missing return something or
1750                 *  is a bug in hotot. Workaround, meantime
1751                 */
1752
1753                 /*$ret=Array();
1754                 return array('$users' => $ret);*/
1755                 return false;
1756         }
1757
1758         $sql_extra = '';
1759         if ($qtype == 'friends') {
1760                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
1761         } elseif ($qtype == 'followers') {
1762                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
1763         }
1764
1765         if ($qtype == 'blocks') {
1766                 $sql_filter = 'AND `blocked` AND NOT `pending`';
1767         } elseif ($qtype == 'incoming') {
1768                 $sql_filter = 'AND `pending`';
1769         } else {
1770                 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
1771         }
1772
1773         // @todo This query most likely can be replaced with a Contact::select...
1774         $r = DBA::toArray(DBA::p(
1775                 "SELECT `id`
1776                 FROM `contact`
1777                 WHERE `uid` = ?
1778                 AND NOT `self`
1779                 $sql_filter
1780                 $sql_extra
1781                 ORDER BY `nick`
1782                 LIMIT ?, ?",
1783                 $uid,
1784                 $start,
1785                 $count
1786         ));
1787
1788         $ret = [];
1789         foreach ($r as $cid) {
1790                 $user = DI::twitterUser()->createFromContactId($cid['id'], $uid, false)->toArray();
1791                 // "uid" is only needed for some internal stuff, so remove it from here
1792                 unset($user['uid']);
1793
1794                 if ($user) {
1795                         $ret[] = $user;
1796                 }
1797         }
1798
1799         return ['user' => $ret];
1800 }
1801
1802 /**
1803  * Returns the list of friends of the provided user
1804  *
1805  * @deprecated By Twitter API in favor of friends/list
1806  *
1807  * @param string $type Either "json" or "xml"
1808  * @return boolean|string|array
1809  * @throws BadRequestException
1810  * @throws ForbiddenException
1811  */
1812 function api_statuses_friends($type)
1813 {
1814         $data =  api_statuses_f("friends");
1815         if ($data === false) {
1816                 return false;
1817         }
1818         return DI::apiResponse()->formatData("users", $type, $data);
1819 }
1820
1821 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
1822
1823 /**
1824  * Returns the list of followers of the provided user
1825  *
1826  * @deprecated By Twitter API in favor of friends/list
1827  *
1828  * @param string $type Either "json" or "xml"
1829  * @return boolean|string|array
1830  * @throws BadRequestException
1831  * @throws ForbiddenException
1832  */
1833 function api_statuses_followers($type)
1834 {
1835         $data = api_statuses_f("followers");
1836         if ($data === false) {
1837                 return false;
1838         }
1839         return DI::apiResponse()->formatData("users", $type, $data);
1840 }
1841
1842 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
1843
1844 /**
1845  * Returns the list of blocked users
1846  *
1847  * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
1848  *
1849  * @param string $type Either "json" or "xml"
1850  *
1851  * @return boolean|string|array
1852  * @throws BadRequestException
1853  * @throws ForbiddenException
1854  */
1855 function api_blocks_list($type)
1856 {
1857         $data =  api_statuses_f('blocks');
1858         if ($data === false) {
1859                 return false;
1860         }
1861         return DI::apiResponse()->formatData("users", $type, $data);
1862 }
1863
1864 api_register_func('api/blocks/list', 'api_blocks_list', true);
1865
1866 /**
1867  * Returns the list of pending users IDs
1868  *
1869  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
1870  *
1871  * @param string $type Either "json" or "xml"
1872  *
1873  * @return boolean|string|array
1874  * @throws BadRequestException
1875  * @throws ForbiddenException
1876  */
1877 function api_friendships_incoming($type)
1878 {
1879         $data =  api_statuses_f('incoming');
1880         if ($data === false) {
1881                 return false;
1882         }
1883
1884         $ids = [];
1885         foreach ($data['user'] as $user) {
1886                 $ids[] = $user['id'];
1887         }
1888
1889         return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
1890 }
1891
1892 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
1893
1894 /**
1895  * Sends a new direct message.
1896  *
1897  * @param string $type Return type (atom, rss, xml, json)
1898  *
1899  * @return array|string
1900  * @throws BadRequestException
1901  * @throws ForbiddenException
1902  * @throws ImagickException
1903  * @throws InternalServerErrorException
1904  * @throws NotFoundException
1905  * @throws UnauthorizedException
1906  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
1907  */
1908 function api_direct_messages_new($type)
1909 {
1910         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1911         $uid = BaseApi::getCurrentUserID();
1912
1913         if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
1914                 return;
1915         }
1916
1917         $sender = DI::twitterUser()->createFromUserId($uid, true)->toArray();
1918
1919         $cid = BaseApi::getContactIDForSearchterm($_POST['screen_name'] ?? '', $_POST['user_id'] ?? 0, $uid);
1920         if (empty($cid)) {
1921                 throw new NotFoundException('Recipient not found');
1922         }
1923
1924         $replyto = '';
1925         if (!empty($_REQUEST['replyto'])) {
1926                 $mail    = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
1927                 $replyto = $mail['parent-uri'];
1928                 $sub     = $mail['title'];
1929         } else {
1930                 if (!empty($_REQUEST['title'])) {
1931                         $sub = $_REQUEST['title'];
1932                 } else {
1933                         $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
1934                 }
1935         }
1936
1937         $cdata = Contact::getPublicAndUserContactID($cid, $uid);
1938
1939         $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
1940
1941         if ($id > -1) {
1942                 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
1943                 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid, true)->toArray(), $sender);
1944         } else {
1945                 $ret = ["error" => $id];
1946         }
1947
1948         return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
1949 }
1950
1951 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
1952
1953 /**
1954  * delete a direct_message from mail table through api
1955  *
1956  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
1957  * @return string|array
1958  * @throws BadRequestException
1959  * @throws ForbiddenException
1960  * @throws ImagickException
1961  * @throws InternalServerErrorException
1962  * @throws UnauthorizedException
1963  * @see   https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
1964  */
1965 function api_direct_messages_destroy($type)
1966 {
1967         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1968         $uid = BaseApi::getCurrentUserID();
1969
1970         //required
1971         $id = $_REQUEST['id'] ?? 0;
1972         // optional
1973         $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
1974         $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
1975         /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
1976
1977         // error if no id or parenturi specified (for clients posting parent-uri as well)
1978         if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
1979                 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
1980                 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
1981         }
1982
1983         // BadRequestException if no id specified (for clients using Twitter API)
1984         if ($id == 0) {
1985                 throw new BadRequestException('Message id not specified');
1986         }
1987
1988         // add parent-uri to sql command if specified by calling app
1989         $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
1990
1991         // error message if specified id is not in database
1992         if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
1993                 if ($verbose == "true") {
1994                         $answer = ['result' => 'error', 'message' => 'message id not in database'];
1995                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
1996                 }
1997                 /// @todo BadRequestException ok for Twitter API clients?
1998                 throw new BadRequestException('message id not in database');
1999         }
2000
2001         // delete message
2002         $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
2003
2004         if ($verbose == "true") {
2005                 if ($result) {
2006                         // return success
2007                         $answer = ['result' => 'ok', 'message' => 'message deleted'];
2008                         return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
2009                 } else {
2010                         $answer = ['result' => 'error', 'message' => 'unknown error'];
2011                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2012                 }
2013         }
2014         /// @todo return JSON data like Twitter API not yet implemented
2015 }
2016
2017 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2018
2019 /**
2020  * Unfollow Contact
2021  *
2022  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2023  * @return string|array
2024  * @throws HTTPException\BadRequestException
2025  * @throws HTTPException\ExpectationFailedException
2026  * @throws HTTPException\ForbiddenException
2027  * @throws HTTPException\InternalServerErrorException
2028  * @throws HTTPException\NotFoundException
2029  * @see   https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
2030  */
2031 function api_friendships_destroy($type)
2032 {
2033         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2034         $uid = BaseApi::getCurrentUserID();
2035
2036         $owner = User::getOwnerDataById($uid);
2037         if (!$owner) {
2038                 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
2039                 throw new HTTPException\NotFoundException('Error Processing Request');
2040         }
2041
2042         $contact_id = $_REQUEST['user_id'] ?? 0;
2043
2044         if (empty($contact_id)) {
2045                 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
2046                 throw new HTTPException\BadRequestException('no user_id specified');
2047         }
2048
2049         // Get Contact by given id
2050         $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
2051
2052         if(!DBA::isResult($contact)) {
2053                 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
2054                 throw new HTTPException\NotFoundException('no contact found to given ID');
2055         }
2056
2057         $url = $contact['url'];
2058
2059         $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
2060                         $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
2061                         Strings::normaliseLink($url), $url];
2062         $contact = DBA::selectFirst('contact', [], $condition);
2063
2064         if (!DBA::isResult($contact)) {
2065                 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
2066                 throw new HTTPException\NotFoundException('Not following Contact');
2067         }
2068
2069         try {
2070                 $result = Contact::terminateFriendship($owner, $contact);
2071
2072                 if ($result === null) {
2073                         Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
2074                         throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
2075                 }
2076
2077                 if ($result === false) {
2078                         throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
2079                 }
2080         } catch (Exception $e) {
2081                 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
2082                 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
2083         }
2084
2085         // "uid" is only needed for some internal stuff, so remove it from here
2086         unset($contact['uid']);
2087
2088         // Set screen_name since Twidere requests it
2089         $contact['screen_name'] = $contact['nick'];
2090
2091         return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
2092 }
2093
2094 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
2095
2096 /**
2097  *
2098  * @param string $type Return type (atom, rss, xml, json)
2099  * @param string $box
2100  * @param string $verbose
2101  *
2102  * @return array|string
2103  * @throws BadRequestException
2104  * @throws ForbiddenException
2105  * @throws ImagickException
2106  * @throws InternalServerErrorException
2107  * @throws UnauthorizedException
2108  */
2109 function api_direct_messages_box($type, $box, $verbose)
2110 {
2111         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2112         $uid = BaseApi::getCurrentUserID();
2113
2114         // params
2115         $count = $_GET['count'] ?? 20;
2116         $page = $_REQUEST['page'] ?? 1;
2117
2118         $since_id = $_REQUEST['since_id'] ?? 0;
2119         $max_id = $_REQUEST['max_id'] ?? 0;
2120
2121         $user_id = $_REQUEST['user_id'] ?? '';
2122         $screen_name = $_REQUEST['screen_name'] ?? '';
2123
2124         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2125
2126         $profile_url = $user_info["url"];
2127
2128         // pagination
2129         $start = max(0, ($page - 1) * $count);
2130
2131         $sql_extra = "";
2132
2133         // filters
2134         if ($box=="sentbox") {
2135                 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
2136         } elseif ($box == "conversation") {
2137                 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '')  . "'";
2138         } elseif ($box == "all") {
2139                 $sql_extra = "true";
2140         } elseif ($box == "inbox") {
2141                 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
2142         }
2143
2144         if ($max_id > 0) {
2145                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
2146         }
2147
2148         if ($user_id != "") {
2149                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2150         } elseif ($screen_name !="") {
2151                 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
2152         }
2153
2154         $r = DBA::toArray(DBA::p(
2155                 "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 ?,?",
2156                 $uid,
2157                 $since_id,
2158                 $start,
2159                 $count
2160         ));
2161         if ($verbose == "true" && !DBA::isResult($r)) {
2162                 $answer = ['result' => 'error', 'message' => 'no mails available'];
2163                 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
2164         }
2165
2166         $ret = [];
2167         foreach ($r as $item) {
2168                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
2169                         $recipient = $user_info;
2170                         $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2171                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
2172                         $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2173                         $sender = $user_info;
2174                 }
2175
2176                 if (isset($recipient) && isset($sender)) {
2177                         $ret[] = api_format_messages($item, $recipient, $sender);
2178                 }
2179         }
2180
2181         return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2182 }
2183
2184 /**
2185  * Returns the most recent direct messages sent by the user.
2186  *
2187  * @param string $type Return type (atom, rss, xml, json)
2188  *
2189  * @return array|string
2190  * @throws BadRequestException
2191  * @throws ForbiddenException
2192  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
2193  */
2194 function api_direct_messages_sentbox($type)
2195 {
2196         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2197         return api_direct_messages_box($type, "sentbox", $verbose);
2198 }
2199
2200 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
2201
2202 /**
2203  * Returns the most recent direct messages sent to the user.
2204  *
2205  * @param string $type Return type (atom, rss, xml, json)
2206  *
2207  * @return array|string
2208  * @throws BadRequestException
2209  * @throws ForbiddenException
2210  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
2211  */
2212 function api_direct_messages_inbox($type)
2213 {
2214         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2215         return api_direct_messages_box($type, "inbox", $verbose);
2216 }
2217
2218 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
2219
2220 /**
2221  *
2222  * @param string $type Return type (atom, rss, xml, json)
2223  *
2224  * @return array|string
2225  * @throws BadRequestException
2226  * @throws ForbiddenException
2227  */
2228 function api_direct_messages_all($type)
2229 {
2230         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2231         return api_direct_messages_box($type, "all", $verbose);
2232 }
2233
2234 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
2235
2236 /**
2237  *
2238  * @param string $type Return type (atom, rss, xml, json)
2239  *
2240  * @return array|string
2241  * @throws BadRequestException
2242  * @throws ForbiddenException
2243  */
2244 function api_direct_messages_conversation($type)
2245 {
2246         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2247         return api_direct_messages_box($type, "conversation", $verbose);
2248 }
2249
2250 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
2251
2252 /**
2253  * list all photos of the authenticated user
2254  *
2255  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2256  * @return string|array
2257  * @throws ForbiddenException
2258  * @throws InternalServerErrorException
2259  */
2260 function api_fr_photos_list($type)
2261 {
2262         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2263         $uid = BaseApi::getCurrentUserID();
2264
2265         $r = DBA::toArray(DBA::p(
2266                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
2267                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
2268                 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
2269                 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
2270         ));
2271         $typetoext = [
2272                 'image/jpeg' => 'jpg',
2273                 'image/png' => 'png',
2274                 'image/gif' => 'gif'
2275         ];
2276         $data = ['photo'=>[]];
2277         if (DBA::isResult($r)) {
2278                 foreach ($r as $rr) {
2279                         $photo = [];
2280                         $photo['id'] = $rr['resource-id'];
2281                         $photo['album'] = $rr['album'];
2282                         $photo['filename'] = $rr['filename'];
2283                         $photo['type'] = $rr['type'];
2284                         $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
2285                         $photo['created'] = $rr['created'];
2286                         $photo['edited'] = $rr['edited'];
2287                         $photo['desc'] = $rr['desc'];
2288
2289                         if ($type == "xml") {
2290                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
2291                         } else {
2292                                 $photo['thumb'] = $thumb;
2293                                 $data['photo'][] = $photo;
2294                         }
2295                 }
2296         }
2297         return DI::apiResponse()->formatData("photos", $type, $data);
2298 }
2299
2300 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2301
2302 /**
2303  * upload a new photo or change an existing photo
2304  *
2305  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2306  * @return string|array
2307  * @throws BadRequestException
2308  * @throws ForbiddenException
2309  * @throws ImagickException
2310  * @throws InternalServerErrorException
2311  * @throws NotFoundException
2312  */
2313 function api_fr_photo_create_update($type)
2314 {
2315         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2316         $uid = BaseApi::getCurrentUserID();
2317
2318         // input params
2319         $photo_id  = $_REQUEST['photo_id']  ?? null;
2320         $desc      = $_REQUEST['desc']      ?? null;
2321         $album     = $_REQUEST['album']     ?? null;
2322         $album_new = $_REQUEST['album_new'] ?? null;
2323         $allow_cid = $_REQUEST['allow_cid'] ?? null;
2324         $deny_cid  = $_REQUEST['deny_cid' ] ?? null;
2325         $allow_gid = $_REQUEST['allow_gid'] ?? null;
2326         $deny_gid  = $_REQUEST['deny_gid' ] ?? null;
2327         $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
2328
2329         // do several checks on input parameters
2330         // we do not allow calls without album string
2331         if ($album == null) {
2332                 throw new BadRequestException("no albumname specified");
2333         }
2334         // if photo_id == null --> we are uploading a new photo
2335         if ($photo_id == null) {
2336                 $mode = "create";
2337
2338                 // error if no media posted in create-mode
2339                 if (empty($_FILES['media'])) {
2340                         // Output error
2341                         throw new BadRequestException("no media data submitted");
2342                 }
2343
2344                 // album_new will be ignored in create-mode
2345                 $album_new = "";
2346         } else {
2347                 $mode = "update";
2348
2349                 // check if photo is existing in databasei
2350                 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
2351                         throw new BadRequestException("photo not available");
2352                 }
2353         }
2354
2355         // checks on acl strings provided by clients
2356         $acl_input_error = false;
2357         $acl_input_error |= check_acl_input($allow_cid, $uid);
2358         $acl_input_error |= check_acl_input($deny_cid, $uid);
2359         $acl_input_error |= check_acl_input($allow_gid, $uid);
2360         $acl_input_error |= check_acl_input($deny_gid, $uid);
2361         if ($acl_input_error) {
2362                 throw new BadRequestException("acl data invalid");
2363         }
2364         // now let's upload the new media in create-mode
2365         if ($mode == "create") {
2366                 $media = $_FILES['media'];
2367                 $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);
2368
2369                 // return success of updating or error message
2370                 if (!is_null($data)) {
2371                         return DI::apiResponse()->formatData("photo_create", $type, $data);
2372                 } else {
2373                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
2374                 }
2375         }
2376
2377         // now let's do the changes in update-mode
2378         if ($mode == "update") {
2379                 $updated_fields = [];
2380
2381                 if (!is_null($desc)) {
2382                         $updated_fields['desc'] = $desc;
2383                 }
2384
2385                 if (!is_null($album_new)) {
2386                         $updated_fields['album'] = $album_new;
2387                 }
2388
2389                 if (!is_null($allow_cid)) {
2390                         $allow_cid = trim($allow_cid);
2391                         $updated_fields['allow_cid'] = $allow_cid;
2392                 }
2393
2394                 if (!is_null($deny_cid)) {
2395                         $deny_cid = trim($deny_cid);
2396                         $updated_fields['deny_cid'] = $deny_cid;
2397                 }
2398
2399                 if (!is_null($allow_gid)) {
2400                         $allow_gid = trim($allow_gid);
2401                         $updated_fields['allow_gid'] = $allow_gid;
2402                 }
2403
2404                 if (!is_null($deny_gid)) {
2405                         $deny_gid = trim($deny_gid);
2406                         $updated_fields['deny_gid'] = $deny_gid;
2407                 }
2408
2409                 $result = false;
2410                 if (count($updated_fields) > 0) {
2411                         $nothingtodo = false;
2412                         $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
2413                 } else {
2414                         $nothingtodo = true;
2415                 }
2416
2417                 if (!empty($_FILES['media'])) {
2418                         $nothingtodo = false;
2419                         $media = $_FILES['media'];
2420                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
2421                         if (!is_null($data)) {
2422                                 return DI::apiResponse()->formatData("photo_update", $type, $data);
2423                         }
2424                 }
2425
2426                 // return success of updating or error message
2427                 if ($result) {
2428                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
2429                         return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
2430                 } else {
2431                         if ($nothingtodo) {
2432                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
2433                                 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
2434                         }
2435                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
2436                 }
2437         }
2438         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
2439 }
2440
2441 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
2442 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
2443
2444 /**
2445  * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
2446  *
2447  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2448  * @return string|array
2449  * @throws BadRequestException
2450  * @throws ForbiddenException
2451  * @throws InternalServerErrorException
2452  * @throws NotFoundException
2453  */
2454 function api_fr_photo_detail($type)
2455 {
2456         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2457         $uid = BaseApi::getCurrentUserID();
2458
2459         if (empty($_REQUEST['photo_id'])) {
2460                 throw new BadRequestException("No photo id.");
2461         }
2462
2463         $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
2464         $photo_id = $_REQUEST['photo_id'];
2465
2466         // prepare json/xml output with data from database for the requested photo
2467         $data = prepare_photo_data($type, $scale, $photo_id, $uid);
2468
2469         return DI::apiResponse()->formatData("photo_detail", $type, $data);
2470 }
2471
2472 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2473
2474 /**
2475  * updates the profile image for the user (either a specified profile or the default profile)
2476  *
2477  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2478  *
2479  * @return string|array
2480  * @throws BadRequestException
2481  * @throws ForbiddenException
2482  * @throws ImagickException
2483  * @throws InternalServerErrorException
2484  * @throws NotFoundException
2485  * @see   https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
2486  */
2487 function api_account_update_profile_image($type)
2488 {
2489         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2490         $uid = BaseApi::getCurrentUserID();
2491
2492         // input params
2493         $profile_id = $_REQUEST['profile_id'] ?? 0;
2494
2495         // error if image data is missing
2496         if (empty($_FILES['image'])) {
2497                 throw new BadRequestException("no media data submitted");
2498         }
2499
2500         // check if specified profile id is valid
2501         if ($profile_id != 0) {
2502                 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
2503                 // error message if specified profile id is not in database
2504                 if (!DBA::isResult($profile)) {
2505                         throw new BadRequestException("profile_id not available");
2506                 }
2507                 $is_default_profile = $profile['is-default'];
2508         } else {
2509                 $is_default_profile = 1;
2510         }
2511
2512         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
2513         $media = null;
2514         if (!empty($_FILES['image'])) {
2515                 $media = $_FILES['image'];
2516         } elseif (!empty($_FILES['media'])) {
2517                 $media = $_FILES['media'];
2518         }
2519         // save new profile image
2520         $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
2521
2522         // get filetype
2523         if (is_array($media['type'])) {
2524                 $filetype = $media['type'][0];
2525         } else {
2526                 $filetype = $media['type'];
2527         }
2528         if ($filetype == "image/jpeg") {
2529                 $fileext = "jpg";
2530         } elseif ($filetype == "image/png") {
2531                 $fileext = "png";
2532         } else {
2533                 throw new InternalServerErrorException('Unsupported filetype');
2534         }
2535
2536         // change specified profile or all profiles to the new resource-id
2537         if ($is_default_profile) {
2538                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
2539                 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
2540         } else {
2541                 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
2542                         'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
2543                 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
2544         }
2545
2546         Contact::updateSelfFromUserID($uid, true);
2547
2548         // Update global directory in background
2549         Profile::publishUpdate($uid);
2550
2551         // output for client
2552         if ($data) {
2553                 $skip_status = $_REQUEST['skip_status'] ?? false;
2554         
2555                 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
2556         
2557                 // "verified" isn't used here in the standard
2558                 unset($user_info["verified"]);
2559         
2560                 // "uid" is only needed for some internal stuff, so remove it from here
2561                 unset($user_info['uid']);
2562
2563                 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
2564         } else {
2565                 // SaveMediaToDatabase failed for some reason
2566                 throw new InternalServerErrorException("image upload failed");
2567         }
2568 }
2569
2570 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
2571
2572 /**
2573  * Return all or a specified group of the user with the containing contacts.
2574  *
2575  * @param string $type Return type (atom, rss, xml, json)
2576  *
2577  * @return array|string
2578  * @throws BadRequestException
2579  * @throws ForbiddenException
2580  * @throws ImagickException
2581  * @throws InternalServerErrorException
2582  * @throws UnauthorizedException
2583  */
2584 function api_friendica_group_show($type)
2585 {
2586         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2587         $uid = BaseApi::getCurrentUserID();
2588
2589         // params
2590         $gid = $_REQUEST['gid'] ?? 0;
2591
2592         // get data of the specified group id or all groups if not specified
2593         if ($gid != 0) {
2594                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
2595
2596                 // error message if specified gid is not in database
2597                 if (!DBA::isResult($groups)) {
2598                         throw new BadRequestException("gid not available");
2599                 }
2600         } else {
2601                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
2602         }
2603
2604         // loop through all groups and retrieve all members for adding data in the user array
2605         $grps = [];
2606         foreach ($groups as $rr) {
2607                 $members = Contact\Group::getById($rr['id']);
2608                 $users = [];
2609
2610                 if ($type == "xml") {
2611                         $user_element = "users";
2612                         $k = 0;
2613                         foreach ($members as $member) {
2614                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
2615                                 $users[$k++.":user"] = $user;
2616                         }
2617                 } else {
2618                         $user_element = "user";
2619                         foreach ($members as $member) {
2620                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
2621                                 $users[] = $user;
2622                         }
2623                 }
2624                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
2625         }
2626         return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
2627 }
2628
2629 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
2630
2631 /**
2632  * Delete a group.
2633  *
2634  * @param string $type Return type (atom, rss, xml, json)
2635  *
2636  * @return array|string
2637  * @throws BadRequestException
2638  * @throws ForbiddenException
2639  * @throws ImagickException
2640  * @throws InternalServerErrorException
2641  * @throws UnauthorizedException
2642  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
2643  */
2644 function api_lists_destroy($type)
2645 {
2646         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2647         $uid = BaseApi::getCurrentUserID();
2648
2649         // params
2650         $gid = $_REQUEST['list_id'] ?? 0;
2651
2652         // error if no gid specified
2653         if ($gid == 0) {
2654                 throw new BadRequestException('gid not specified');
2655         }
2656
2657         // get data of the specified group id
2658         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
2659         // error message if specified gid is not in database
2660         if (!$group) {
2661                 throw new BadRequestException('gid not available');
2662         }
2663
2664         if (Group::remove($gid)) {
2665                 $list = [
2666                         'name' => $group['name'],
2667                         'id' => intval($gid),
2668                         'id_str' => (string) $gid,
2669                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
2670                 ];
2671
2672                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
2673         }
2674 }
2675
2676 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
2677
2678 /**
2679  * Create the specified group with the posted array of contacts.
2680  *
2681  * @param string $type Return type (atom, rss, xml, json)
2682  *
2683  * @return array|string
2684  * @throws BadRequestException
2685  * @throws ForbiddenException
2686  * @throws ImagickException
2687  * @throws InternalServerErrorException
2688  * @throws UnauthorizedException
2689  */
2690 function api_friendica_group_create($type)
2691 {
2692         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2693         $uid = BaseApi::getCurrentUserID();
2694
2695         // params
2696         $name = $_REQUEST['name'] ?? '';
2697         $json = json_decode($_POST['json'], true);
2698         $users = $json['user'];
2699
2700         $success = group_create($name, $uid, $users);
2701
2702         return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
2703 }
2704
2705 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
2706
2707 /**
2708  * Create a new group.
2709  *
2710  * @param string $type Return type (atom, rss, xml, json)
2711  *
2712  * @return array|string
2713  * @throws BadRequestException
2714  * @throws ForbiddenException
2715  * @throws ImagickException
2716  * @throws InternalServerErrorException
2717  * @throws UnauthorizedException
2718  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
2719  */
2720 function api_lists_create($type)
2721 {
2722         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2723         $uid = BaseApi::getCurrentUserID();
2724
2725         // params
2726         $name = $_REQUEST['name'] ?? '';
2727
2728         $success = group_create($name, $uid);
2729         if ($success['success']) {
2730                 $grp = [
2731                         'name' => $success['name'],
2732                         'id' => intval($success['gid']),
2733                         'id_str' => (string) $success['gid'],
2734                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
2735                 ];
2736
2737                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
2738         }
2739 }
2740
2741 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
2742
2743 /**
2744  * Update the specified group with the posted array of contacts.
2745  *
2746  * @param string $type Return type (atom, rss, xml, json)
2747  *
2748  * @return array|string
2749  * @throws BadRequestException
2750  * @throws ForbiddenException
2751  * @throws ImagickException
2752  * @throws InternalServerErrorException
2753  * @throws UnauthorizedException
2754  */
2755 function api_friendica_group_update($type)
2756 {
2757         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2758         $uid = BaseApi::getCurrentUserID();
2759
2760         // params
2761         $gid = $_REQUEST['gid'] ?? 0;
2762         $name = $_REQUEST['name'] ?? '';
2763         $json = json_decode($_POST['json'], true);
2764         $users = $json['user'];
2765
2766         // error if no name specified
2767         if ($name == "") {
2768                 throw new BadRequestException('group name not specified');
2769         }
2770
2771         // error if no gid specified
2772         if ($gid == "") {
2773                 throw new BadRequestException('gid not specified');
2774         }
2775
2776         // remove members
2777         $members = Contact\Group::getById($gid);
2778         foreach ($members as $member) {
2779                 $cid = $member['id'];
2780                 foreach ($users as $user) {
2781                         $found = ($user['cid'] == $cid ? true : false);
2782                 }
2783                 if (!isset($found) || !$found) {
2784                         $gid = Group::getIdByName($uid, $name);
2785                         Group::removeMember($gid, $cid);
2786                 }
2787         }
2788
2789         // add members
2790         $erroraddinguser = false;
2791         $errorusers = [];
2792         foreach ($users as $user) {
2793                 $cid = $user['cid'];
2794
2795                 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
2796                         Group::addMember($gid, $cid);
2797                 } else {
2798                         $erroraddinguser = true;
2799                         $errorusers[] = $cid;
2800                 }
2801         }
2802
2803         // return success message incl. missing users in array
2804         $status = ($erroraddinguser ? "missing user" : "ok");
2805         $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
2806         return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
2807 }
2808
2809 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
2810
2811 /**
2812  * Update information about a group.
2813  *
2814  * @param string $type Return type (atom, rss, xml, json)
2815  *
2816  * @return array|string
2817  * @throws BadRequestException
2818  * @throws ForbiddenException
2819  * @throws ImagickException
2820  * @throws InternalServerErrorException
2821  * @throws UnauthorizedException
2822  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
2823  */
2824 function api_lists_update($type)
2825 {
2826         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2827         $uid = BaseApi::getCurrentUserID();
2828
2829         // params
2830         $gid = $_REQUEST['list_id'] ?? 0;
2831         $name = $_REQUEST['name'] ?? '';
2832
2833         // error if no gid specified
2834         if ($gid == 0) {
2835                 throw new BadRequestException('gid not specified');
2836         }
2837
2838         // get data of the specified group id
2839         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
2840         // error message if specified gid is not in database
2841         if (!$group) {
2842                 throw new BadRequestException('gid not available');
2843         }
2844
2845         if (Group::update($gid, $name)) {
2846                 $list = [
2847                         'name' => $name,
2848                         'id' => intval($gid),
2849                         'id_str' => (string) $gid,
2850                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
2851                 ];
2852
2853                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
2854         }
2855 }
2856
2857 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
2858
2859 /**
2860  * search for direct_messages containing a searchstring through api
2861  *
2862  * @param string $type      Known types are 'atom', 'rss', 'xml' and 'json'
2863  * @param string $box
2864  * @return string|array (success: success=true if found and search_result contains found messages,
2865  *                          success=false if nothing was found, search_result='nothing found',
2866  *                          error: result=error with error message)
2867  * @throws BadRequestException
2868  * @throws ForbiddenException
2869  * @throws ImagickException
2870  * @throws InternalServerErrorException
2871  * @throws UnauthorizedException
2872  */
2873 function api_friendica_direct_messages_search($type, $box = "")
2874 {
2875         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2876         $uid = BaseApi::getCurrentUserID();
2877
2878         // params
2879         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2880         $searchstring = $_REQUEST['searchstring'] ?? '';
2881
2882         // error if no searchstring specified
2883         if ($searchstring == "") {
2884                 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
2885                 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
2886         }
2887
2888         // get data for the specified searchstring
2889         $r = DBA::toArray(DBA::p(
2890                 "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",
2891                 $uid,
2892                 '%'.$searchstring.'%'
2893         ));
2894
2895         $profile_url = $user_info["url"];
2896
2897         // message if nothing was found
2898         if (!DBA::isResult($r)) {
2899                 $success = ['success' => false, 'search_results' => 'problem with query'];
2900         } elseif (count($r) == 0) {
2901                 $success = ['success' => false, 'search_results' => 'nothing found'];
2902         } else {
2903                 $ret = [];
2904                 foreach ($r as $item) {
2905                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
2906                                 $recipient = $user_info;
2907                                 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2908                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
2909                                 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2910                                 $sender = $user_info;
2911                         }
2912
2913                         if (isset($recipient) && isset($sender)) {
2914                                 $ret[] = api_format_messages($item, $recipient, $sender);
2915                         }
2916                 }
2917                 $success = ['success' => true, 'search_results' => $ret];
2918         }
2919
2920         return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
2921 }
2922
2923 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);