]> git.mxchange.org Git - friendica.git/blob - include/api.php
68544754578b97e307036adf0b28315313f70314
[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  * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
692  * returns a 401 status code and an error message if not.
693  *
694  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
695  *
696  * @param string $type Return type (atom, rss, xml, json)
697  * @return array|string
698  * @throws BadRequestException
699  * @throws ForbiddenException
700  * @throws ImagickException
701  * @throws InternalServerErrorException
702  * @throws UnauthorizedException
703  */
704 function api_account_verify_credentials($type)
705 {
706         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
707         $uid = BaseApi::getCurrentUserID();
708
709         unset($_REQUEST['user_id']);
710         unset($_GET['user_id']);
711
712         unset($_REQUEST['screen_name']);
713         unset($_GET['screen_name']);
714
715         $skip_status = $_REQUEST['skip_status'] ?? false;
716
717         $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
718
719         // "verified" isn't used here in the standard
720         unset($user_info["verified"]);
721
722         // "uid" is only needed for some internal stuff, so remove it from here
723         unset($user_info['uid']);
724         
725         return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
726 }
727
728 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
729
730 /**
731  * Deprecated function to upload media.
732  *
733  * @param string $type Return type (atom, rss, xml, json)
734  *
735  * @return array|string
736  * @throws BadRequestException
737  * @throws ForbiddenException
738  * @throws ImagickException
739  * @throws InternalServerErrorException
740  * @throws UnauthorizedException
741  */
742 function api_statuses_mediap($type)
743 {
744         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
745         $uid = BaseApi::getCurrentUserID();
746
747         $a = DI::app();
748
749         $_REQUEST['profile_uid'] = $uid;
750         $_REQUEST['api_source'] = true;
751         $txt = $_REQUEST['status'] ?? '';
752
753         if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
754                 $txt = HTML::toBBCodeVideo($txt);
755                 $config = HTMLPurifier_Config::createDefault();
756                 $config->set('Cache.DefinitionImpl', null);
757                 $purifier = new HTMLPurifier($config);
758                 $txt = $purifier->purify($txt);
759         }
760         $txt = HTML::toBBCode($txt);
761
762         $picture = wall_upload_post($a, false);
763
764         // now that we have the img url in bbcode we can add it to the status and insert the wall item.
765         $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
766         $item_id = item_post($a);
767
768         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
769
770         // output the post that we just posted.
771         $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
772         return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
773 }
774
775 /// @TODO move this to top of file or somewhere better!
776 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
777
778 /**
779  * Updates the user’s current status.
780  *
781  * @param string $type Return type (atom, rss, xml, json)
782  *
783  * @return array|string
784  * @throws BadRequestException
785  * @throws ForbiddenException
786  * @throws ImagickException
787  * @throws InternalServerErrorException
788  * @throws TooManyRequestsException
789  * @throws UnauthorizedException
790  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
791  */
792 function api_statuses_update($type)
793 {
794         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
795         $uid = BaseApi::getCurrentUserID();
796
797         $a = DI::app();
798
799         // convert $_POST array items to the form we use for web posts.
800         if (!empty($_REQUEST['htmlstatus'])) {
801                 $txt = $_REQUEST['htmlstatus'];
802                 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
803                         $txt = HTML::toBBCodeVideo($txt);
804
805                         $config = HTMLPurifier_Config::createDefault();
806                         $config->set('Cache.DefinitionImpl', null);
807
808                         $purifier = new HTMLPurifier($config);
809                         $txt = $purifier->purify($txt);
810
811                         $_REQUEST['body'] = HTML::toBBCode($txt);
812                 }
813         } else {
814                 $_REQUEST['body'] = $_REQUEST['status'] ?? null;
815         }
816
817         $_REQUEST['title'] = $_REQUEST['title'] ?? null;
818
819         $parent = $_REQUEST['in_reply_to_status_id'] ?? null;
820
821         // Twidere sends "-1" if it is no reply ...
822         if ($parent == -1) {
823                 $parent = "";
824         }
825
826         if (ctype_digit($parent)) {
827                 $_REQUEST['parent'] = $parent;
828         } else {
829                 $_REQUEST['parent_uri'] = $parent;
830         }
831
832         if (!empty($_REQUEST['lat']) && !empty($_REQUEST['long'])) {
833                 $_REQUEST['coord'] = sprintf("%s %s", $_REQUEST['lat'], $_REQUEST['long']);
834         }
835         $_REQUEST['profile_uid'] = $uid;
836
837         if (!$parent) {
838                 // Check for throttling (maximum posts per day, week and month)
839                 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
840                 if ($throttle_day > 0) {
841                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
842
843                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
844                         $posts_day = Post::count($condition);
845
846                         if ($posts_day > $throttle_day) {
847                                 logger::info('Daily posting limit reached for user ' . $uid);
848                                 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
849                                 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));
850                         }
851                 }
852
853                 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
854                 if ($throttle_week > 0) {
855                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
856
857                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
858                         $posts_week = Post::count($condition);
859
860                         if ($posts_week > $throttle_week) {
861                                 logger::info('Weekly posting limit reached for user ' . $uid);
862                                 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
863                                 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));
864                         }
865                 }
866
867                 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
868                 if ($throttle_month > 0) {
869                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
870
871                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
872                         $posts_month = Post::count($condition);
873
874                         if ($posts_month > $throttle_month) {
875                                 logger::info('Monthly posting limit reached for user ' . $uid);
876                                 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
877                                 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));
878                         }
879                 }
880         }
881
882         if (!empty($_REQUEST['media_ids'])) {
883                 $ids = explode(',', $_REQUEST['media_ids']);
884         } elseif (!empty($_FILES['media'])) {
885                 // upload the image if we have one
886                 $picture = wall_upload_post($a, false);
887                 if (is_array($picture)) {
888                         $ids[] = $picture['id'];
889                 }
890         }
891
892         $attachments = [];
893         $ressources = [];
894
895         if (!empty($ids)) {
896                 foreach ($ids as $id) {
897                         $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
898                                         INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
899                                                 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
900                                         ORDER BY `photo`.`width` DESC LIMIT 2", $id, $uid));
901
902                         if (!empty($media)) {
903                                 $ressources[] = $media[0]['resource-id'];
904                                 $phototypes = Images::supportedTypes();
905                                 $ext = $phototypes[$media[0]['type']];
906
907                                 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
908                                         'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
909                                         'size' => $media[0]['datasize'],
910                                         'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
911                                         'description' => $media[0]['desc'] ?? '',
912                                         'width' => $media[0]['width'],
913                                         'height' => $media[0]['height']];
914
915                                 if (count($media) > 1) {
916                                         $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
917                                         $attachment['preview-width'] = $media[1]['width'];
918                                         $attachment['preview-height'] = $media[1]['height'];
919                                 }
920                                 $attachments[] = $attachment;
921                         }
922                 }
923
924                 // We have to avoid that the post is rejected because of an empty body
925                 if (empty($_REQUEST['body'])) {
926                         $_REQUEST['body'] = '[hr]';
927                 }
928         }
929
930         if (!empty($attachments)) {
931                 $_REQUEST['attachments'] = $attachments;
932         }
933
934         // set this so that the item_post() function is quiet and doesn't redirect or emit json
935
936         $_REQUEST['api_source'] = true;
937
938         if (empty($_REQUEST['source'])) {
939                 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
940         }
941
942         // call out normal post function
943         $item_id = item_post($a);
944
945         if (!empty($ressources) && !empty($item_id)) {
946                 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
947                 foreach ($ressources as $ressource) {
948                         Photo::setPermissionForRessource($ressource, $uid, $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
949                 }
950         }
951
952         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
953
954         // output the post that we just posted.
955         $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
956         return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
957 }
958
959 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
960 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
961
962 /**
963  * Uploads an image to Friendica.
964  *
965  * @return array
966  * @throws BadRequestException
967  * @throws ForbiddenException
968  * @throws ImagickException
969  * @throws InternalServerErrorException
970  * @throws UnauthorizedException
971  * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
972  */
973 function api_media_upload()
974 {
975         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
976
977         if (empty($_FILES['media'])) {
978                 // Output error
979                 throw new BadRequestException("No media.");
980         }
981
982         $media = wall_upload_post(DI::app(), false);
983         if (!$media) {
984                 // Output error
985                 throw new InternalServerErrorException();
986         }
987
988         $returndata = [];
989         $returndata["media_id"] = $media["id"];
990         $returndata["media_id_string"] = (string)$media["id"];
991         $returndata["size"] = $media["size"];
992         $returndata["image"] = ["w" => $media["width"],
993                                 "h" => $media["height"],
994                                 "image_type" => $media["type"],
995                                 "friendica_preview_url" => $media["preview"]];
996
997         Logger::info('Media uploaded', ['return' => $returndata]);
998
999         return ["media" => $returndata];
1000 }
1001
1002 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1003
1004 /**
1005  * Updates media meta data (picture descriptions)
1006  *
1007  * @param string $type Return type (atom, rss, xml, json)
1008  *
1009  * @return array|string
1010  * @throws BadRequestException
1011  * @throws ForbiddenException
1012  * @throws ImagickException
1013  * @throws InternalServerErrorException
1014  * @throws TooManyRequestsException
1015  * @throws UnauthorizedException
1016  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1017  *
1018  * @todo Compare the corresponding Twitter function for correct return values
1019  */
1020 function api_media_metadata_create($type)
1021 {
1022         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1023         $uid = BaseApi::getCurrentUserID();
1024
1025         $postdata = Network::postdata();
1026
1027         if (empty($postdata)) {
1028                 throw new BadRequestException("No post data");
1029         }
1030
1031         $data = json_decode($postdata, true);
1032         if (empty($data)) {
1033                 throw new BadRequestException("Invalid post data");
1034         }
1035
1036         if (empty($data['media_id']) || empty($data['alt_text'])) {
1037                 throw new BadRequestException("Missing post data values");
1038         }
1039
1040         if (empty($data['alt_text']['text'])) {
1041                 throw new BadRequestException("No alt text.");
1042         }
1043
1044         Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1045
1046         $condition = ['id' => $data['media_id'], 'uid' => $uid];
1047         $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1048         if (!DBA::isResult($photo)) {
1049                 throw new BadRequestException("Metadata not found.");
1050         }
1051
1052         DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1053 }
1054
1055 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1056
1057 /**
1058  * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1059  * The author's most recent status will be returned inline.
1060  *
1061  * @param string $type Return type (atom, rss, xml, json)
1062  * @return array|string
1063  * @throws BadRequestException
1064  * @throws ImagickException
1065  * @throws InternalServerErrorException
1066  * @throws UnauthorizedException
1067  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1068  */
1069 function api_users_show($type)
1070 {
1071         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1072         $uid = BaseApi::getCurrentUserID();
1073
1074         $user_info = DI::twitterUser()->createFromUserId($uid, false)->toArray();
1075
1076         // "uid" is only needed for some internal stuff, so remove it from here
1077         unset($user_info['uid']);
1078
1079         return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
1080 }
1081
1082 api_register_func('api/users/show', 'api_users_show');
1083 api_register_func('api/externalprofile/show', 'api_users_show');
1084
1085 /**
1086  * Search a public user account.
1087  *
1088  * @param string $type Return type (atom, rss, xml, json)
1089  *
1090  * @return array|string
1091  * @throws BadRequestException
1092  * @throws ImagickException
1093  * @throws InternalServerErrorException
1094  * @throws UnauthorizedException
1095  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1096  */
1097 function api_users_search($type)
1098 {
1099         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1100         $uid = BaseApi::getCurrentUserID();
1101
1102         $userlist = [];
1103
1104         if (!empty($_GET['q'])) {
1105                 $contacts = Contact::selectToArray(
1106                         ['id'],
1107                         [
1108                                 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1109                                 $_GET['q'],
1110                                 $_GET['q'],
1111                                 $_GET['q'],
1112                                 $_GET['q'],
1113                         ]
1114                 );
1115
1116                 if (DBA::isResult($contacts)) {
1117                         $k = 0;
1118                         foreach ($contacts as $contact) {
1119                                 $user_info = DI::twitterUser()->createFromContactId($contact['id'], $uid, false)->toArray();
1120
1121                                 if ($type == 'xml') {
1122                                         $userlist[$k++ . ':user'] = $user_info;
1123                                 } else {
1124                                         $userlist[] = $user_info;
1125                                 }
1126                         }
1127                         $userlist = ['users' => $userlist];
1128                 } else {
1129                         throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1130                 }
1131         } else {
1132                 throw new BadRequestException('No search term specified.');
1133         }
1134
1135         return DI::apiResponse()->formatData('users', $type, $userlist);
1136 }
1137
1138 api_register_func('api/users/search', 'api_users_search');
1139
1140 /**
1141  * Return user objects
1142  *
1143  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1144  *
1145  * @param string $type Return format: json or xml
1146  *
1147  * @return array|string
1148  * @throws BadRequestException
1149  * @throws ImagickException
1150  * @throws InternalServerErrorException
1151  * @throws NotFoundException if the results are empty.
1152  * @throws UnauthorizedException
1153  */
1154 function api_users_lookup($type)
1155 {
1156         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1157         $uid = BaseApi::getCurrentUserID();
1158
1159         $users = [];
1160
1161         if (!empty($_REQUEST['user_id'])) {
1162                 foreach (explode(',', $_REQUEST['user_id']) as $cid) {
1163                         if (!empty($cid) && is_numeric($cid)) {
1164                                 $users[] = DI::twitterUser()->createFromContactId((int)$cid, $uid, false)->toArray();
1165                         }
1166                 }
1167         }
1168
1169         if (empty($users)) {
1170                 throw new NotFoundException;
1171         }
1172
1173         return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
1174 }
1175
1176 api_register_func('api/users/lookup', 'api_users_lookup', true);
1177
1178 /**
1179  * Returns statuses that match a specified query.
1180  *
1181  * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1182  *
1183  * @param string $type Return format: json, xml, atom, rss
1184  *
1185  * @return array|string
1186  * @throws BadRequestException if the "q" parameter is missing.
1187  * @throws ForbiddenException
1188  * @throws ImagickException
1189  * @throws InternalServerErrorException
1190  * @throws UnauthorizedException
1191  */
1192 function api_search($type)
1193 {
1194         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1195         $uid = BaseApi::getCurrentUserID();
1196
1197         if (empty($_REQUEST['q'])) {
1198                 throw new BadRequestException('q parameter is required.');
1199         }
1200
1201         $searchTerm = trim(rawurldecode($_REQUEST['q']));
1202
1203         $data = [];
1204         $data['status'] = [];
1205         $count = 15;
1206         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1207         if (!empty($_REQUEST['rpp'])) {
1208                 $count = $_REQUEST['rpp'];
1209         } elseif (!empty($_REQUEST['count'])) {
1210                 $count = $_REQUEST['count'];
1211         }
1212
1213         $since_id = $_REQUEST['since_id'] ?? 0;
1214         $max_id = $_REQUEST['max_id'] ?? 0;
1215         $page = $_REQUEST['page'] ?? 1;
1216
1217         $start = max(0, ($page - 1) * $count);
1218
1219         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1220         if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1221                 $searchTerm = $matches[1];
1222                 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, $uid];
1223                 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1224                 $uriids = [];
1225                 while ($tag = DBA::fetch($tags)) {
1226                         $uriids[] = $tag['uri-id'];
1227                 }
1228                 DBA::close($tags);
1229
1230                 if (empty($uriids)) {
1231                         return DI::apiResponse()->formatData('statuses', $type, $data);
1232                 }
1233
1234                 $condition = ['uri-id' => $uriids];
1235                 if ($exclude_replies) {
1236                         $condition['gravity'] = GRAVITY_PARENT;
1237                 }
1238
1239                 $params['group_by'] = ['uri-id'];
1240         } else {
1241                 $condition = ["`id` > ?
1242                         " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1243                         AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1244                         AND `body` LIKE CONCAT('%',?,'%')",
1245                         $since_id, $uid, $_REQUEST['q']];
1246                 if ($max_id > 0) {
1247                         $condition[0] .= ' AND `id` <= ?';
1248                         $condition[] = $max_id;
1249                 }
1250         }
1251
1252         $statuses = [];
1253
1254         if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1255                 $id = Item::fetchByLink($searchTerm, $uid);
1256                 if (!$id) {
1257                         // Public post
1258                         $id = Item::fetchByLink($searchTerm);
1259                 }
1260
1261                 if (!empty($id)) {
1262                         $statuses = Post::select([], ['id' => $id]);
1263                 }
1264         }
1265
1266         $statuses = $statuses ?: Post::selectForUser($uid, [], $condition, $params);
1267
1268         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1269
1270         $ret = [];
1271         while ($status = DBA::fetch($statuses)) {
1272                 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1273         }
1274         DBA::close($statuses);
1275
1276         $data['status'] = $ret;
1277
1278         return DI::apiResponse()->formatData('statuses', $type, $data);
1279 }
1280
1281 api_register_func('api/search/tweets', 'api_search', true);
1282 api_register_func('api/search', 'api_search', true);
1283
1284 /**
1285  * Returns the most recent statuses posted by the user and the users they follow.
1286  *
1287  * @see  https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1288  *
1289  * @param string $type Return type (atom, rss, xml, json)
1290  *
1291  * @return array|string
1292  * @throws BadRequestException
1293  * @throws ForbiddenException
1294  * @throws ImagickException
1295  * @throws InternalServerErrorException
1296  * @throws UnauthorizedException
1297  * @todo Optional parameters
1298  * @todo Add reply info
1299  */
1300 function api_statuses_home_timeline($type)
1301 {
1302         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1303         $uid = BaseApi::getCurrentUserID();
1304
1305         unset($_REQUEST['user_id']);
1306         unset($_GET['user_id']);
1307
1308         unset($_REQUEST['screen_name']);
1309         unset($_GET['screen_name']);
1310
1311         // get last network messages
1312
1313         // params
1314         $count = $_REQUEST['count'] ?? 20;
1315         $page = $_REQUEST['page']?? 0;
1316         $since_id = $_REQUEST['since_id'] ?? 0;
1317         $max_id = $_REQUEST['max_id'] ?? 0;
1318         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1319         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1320
1321         $start = max(0, ($page - 1) * $count);
1322
1323         $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1324                 $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1325
1326         if ($max_id > 0) {
1327                 $condition[0] .= " AND `id` <= ?";
1328                 $condition[] = $max_id;
1329         }
1330         if ($exclude_replies) {
1331                 $condition[0] .= ' AND `gravity` = ?';
1332                 $condition[] = GRAVITY_PARENT;
1333         }
1334         if ($conversation_id > 0) {
1335                 $condition[0] .= " AND `parent` = ?";
1336                 $condition[] = $conversation_id;
1337         }
1338
1339         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1340         $statuses = Post::selectForUser($uid, [], $condition, $params);
1341
1342         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1343
1344         $ret = [];
1345         $idarray = [];
1346         while ($status = DBA::fetch($statuses)) {
1347                 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1348                 $idarray[] = intval($status['id']);
1349         }
1350         DBA::close($statuses);
1351
1352         if (!empty($idarray)) {
1353                 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1354                 if ($unseen) {
1355                         Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1356                 }
1357         }
1358
1359         return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1360 }
1361
1362
1363 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1364 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1365
1366 /**
1367  * Returns the most recent statuses from public users.
1368  *
1369  * @param string $type Return type (atom, rss, xml, json)
1370  *
1371  * @return array|string
1372  * @throws BadRequestException
1373  * @throws ForbiddenException
1374  * @throws ImagickException
1375  * @throws InternalServerErrorException
1376  * @throws UnauthorizedException
1377  */
1378 function api_statuses_public_timeline($type)
1379 {
1380         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1381         $uid = BaseApi::getCurrentUserID();
1382
1383         // get last network messages
1384
1385         // params
1386         $count = $_REQUEST['count'] ?? 20;
1387         $page = $_REQUEST['page'] ?? 1;
1388         $since_id = $_REQUEST['since_id'] ?? 0;
1389         $max_id = $_REQUEST['max_id'] ?? 0;
1390         $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1391         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1392
1393         $start = max(0, ($page - 1) * $count);
1394
1395         if ($exclude_replies && !$conversation_id) {
1396                 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1397                         GRAVITY_PARENT, $since_id, Item::PUBLIC];
1398
1399                 if ($max_id > 0) {
1400                         $condition[0] .= " AND `id` <= ?";
1401                         $condition[] = $max_id;
1402                 }
1403
1404                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1405                 $statuses = Post::selectForUser($uid, [], $condition, $params);
1406         } else {
1407                 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1408                         GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1409
1410                 if ($max_id > 0) {
1411                         $condition[0] .= " AND `id` <= ?";
1412                         $condition[] = $max_id;
1413                 }
1414                 if ($conversation_id > 0) {
1415                         $condition[0] .= " AND `parent` = ?";
1416                         $condition[] = $conversation_id;
1417                 }
1418
1419                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1420                 $statuses = Post::selectForUser($uid, [], $condition, $params);
1421         }
1422
1423         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1424
1425         $ret = [];
1426         while ($status = DBA::fetch($statuses)) {
1427                 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1428         }
1429         DBA::close($statuses);
1430
1431         return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1432 }
1433
1434 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1435
1436 /**
1437  * Returns the most recent statuses posted by users this node knows about.
1438  *
1439  * @param string $type Return format: json, xml, atom, rss
1440  * @return array|string
1441  * @throws BadRequestException
1442  * @throws ForbiddenException
1443  * @throws ImagickException
1444  * @throws InternalServerErrorException
1445  * @throws UnauthorizedException
1446  */
1447 function api_statuses_networkpublic_timeline($type)
1448 {
1449         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1450         $uid = BaseApi::getCurrentUserID();
1451
1452         $since_id = $_REQUEST['since_id'] ?? 0;
1453         $max_id   = $_REQUEST['max_id'] ?? 0;
1454
1455         // pagination
1456         $count = $_REQUEST['count'] ?? 20;
1457         $page  = $_REQUEST['page'] ?? 1;
1458
1459         $start = max(0, ($page - 1) * $count);
1460
1461         $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1462                 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1463
1464         if ($max_id > 0) {
1465                 $condition[0] .= " AND `id` <= ?";
1466                 $condition[] = $max_id;
1467         }
1468
1469         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1470         $statuses = Post::selectForUser($uid, Item::DISPLAY_FIELDLIST, $condition, $params);
1471
1472         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1473
1474         $ret = [];
1475         while ($status = DBA::fetch($statuses)) {
1476                 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1477         }
1478         DBA::close($statuses);
1479
1480         return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1481 }
1482
1483 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1484
1485 /**
1486  * Returns a single status.
1487  *
1488  * @param string $type Return type (atom, rss, xml, json)
1489  *
1490  * @return array|string
1491  * @throws BadRequestException
1492  * @throws ForbiddenException
1493  * @throws ImagickException
1494  * @throws InternalServerErrorException
1495  * @throws UnauthorizedException
1496  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1497  */
1498 function api_statuses_show($type)
1499 {
1500         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1501         $uid = BaseApi::getCurrentUserID();
1502
1503         // params
1504         $id = intval(DI::args()->getArgv()[3] ?? 0);
1505
1506         if ($id == 0) {
1507                 $id = intval($_REQUEST['id'] ?? 0);
1508         }
1509
1510         // Hotot workaround
1511         if ($id == 0) {
1512                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1513         }
1514
1515         logger::notice('API: api_statuses_show: ' . $id);
1516
1517         $conversation = !empty($_REQUEST['conversation']);
1518
1519         // try to fetch the item for the local user - or the public item, if there is no local one
1520         $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1521         if (!DBA::isResult($uri_item)) {
1522                 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1523         }
1524
1525         $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1526         if (!DBA::isResult($item)) {
1527                 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1528         }
1529
1530         $id = $item['id'];
1531
1532         if ($conversation) {
1533                 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1534                 $params = ['order' => ['id' => true]];
1535         } else {
1536                 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1537                 $params = [];
1538         }
1539
1540         $statuses = Post::selectForUser($uid, [], $condition, $params);
1541
1542         /// @TODO How about copying this to above methods which don't check $r ?
1543         if (!DBA::isResult($statuses)) {
1544                 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1545         }
1546
1547         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1548
1549         $ret = [];
1550         while ($status = DBA::fetch($statuses)) {
1551                 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1552         }
1553         DBA::close($statuses);
1554
1555         if ($conversation) {
1556                 $data = ['status' => $ret];
1557                 return DI::apiResponse()->formatData("statuses", $type, $data);
1558         } else {
1559                 $data = ['status' => $ret[0]];
1560                 return DI::apiResponse()->formatData("status", $type, $data);
1561         }
1562 }
1563
1564 api_register_func('api/statuses/show', 'api_statuses_show', true);
1565
1566 /**
1567  *
1568  * @param string $type Return type (atom, rss, xml, json)
1569  *
1570  * @return array|string
1571  * @throws BadRequestException
1572  * @throws ForbiddenException
1573  * @throws ImagickException
1574  * @throws InternalServerErrorException
1575  * @throws UnauthorizedException
1576  * @todo nothing to say?
1577  */
1578 function api_conversation_show($type)
1579 {
1580         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1581         $uid = BaseApi::getCurrentUserID();
1582
1583         // params
1584         $id       = intval(DI::args()->getArgv()[3]           ?? 0);
1585         $since_id = intval($_REQUEST['since_id'] ?? 0);
1586         $max_id   = intval($_REQUEST['max_id']   ?? 0);
1587         $count    = intval($_REQUEST['count']    ?? 20);
1588         $page     = intval($_REQUEST['page']     ?? 1);
1589
1590         $start = max(0, ($page - 1) * $count);
1591
1592         if ($id == 0) {
1593                 $id = intval($_REQUEST['id'] ?? 0);
1594         }
1595
1596         // Hotot workaround
1597         if ($id == 0) {
1598                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1599         }
1600
1601         Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1602
1603         // try to fetch the item for the local user - or the public item, if there is no local one
1604         $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1605         if (!DBA::isResult($item)) {
1606                 throw new BadRequestException("There is no status with the id $id.");
1607         }
1608
1609         $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1610         if (!DBA::isResult($parent)) {
1611                 throw new BadRequestException("There is no status with this id.");
1612         }
1613
1614         $id = $parent['id'];
1615
1616         $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1617                 $id, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1618
1619         if ($max_id > 0) {
1620                 $condition[0] .= " AND `id` <= ?";
1621                 $condition[] = $max_id;
1622         }
1623
1624         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1625         $statuses = Post::selectForUser($uid, [], $condition, $params);
1626
1627         if (!DBA::isResult($statuses)) {
1628                 throw new BadRequestException("There is no status with id $id.");
1629         }
1630
1631         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1632
1633         $ret = [];
1634         while ($status = DBA::fetch($statuses)) {
1635                 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1636         }
1637         DBA::close($statuses);
1638
1639         $data = ['status' => $ret];
1640         return DI::apiResponse()->formatData("statuses", $type, $data);
1641 }
1642
1643 api_register_func('api/conversation/show', 'api_conversation_show', true);
1644 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1645
1646 /**
1647  * Repeats a status.
1648  *
1649  * @param string $type Return type (atom, rss, xml, json)
1650  *
1651  * @return array|string
1652  * @throws BadRequestException
1653  * @throws ForbiddenException
1654  * @throws ImagickException
1655  * @throws InternalServerErrorException
1656  * @throws UnauthorizedException
1657  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1658  */
1659 function api_statuses_repeat($type)
1660 {
1661         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1662         $uid = BaseApi::getCurrentUserID();
1663
1664         // params
1665         $id = intval(DI::args()->getArgv()[3] ?? 0);
1666
1667         if ($id == 0) {
1668                 $id = intval($_REQUEST['id'] ?? 0);
1669         }
1670
1671         // Hotot workaround
1672         if ($id == 0) {
1673                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1674         }
1675
1676         logger::notice('API: api_statuses_repeat: ' . $id);
1677
1678         $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1679         $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1680
1681         if (DBA::isResult($item) && !empty($item['body'])) {
1682                 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1683                         if (!Item::performActivity($id, 'announce', $uid)) {
1684                                 throw new InternalServerErrorException();
1685                         }
1686
1687                         $item_id = $id;
1688                 } else {
1689                         if (strpos($item['body'], "[/share]") !== false) {
1690                                 $pos = strpos($item['body'], "[share");
1691                                 $post = substr($item['body'], $pos);
1692                         } else {
1693                                 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1694
1695                                 if (!empty($item['title'])) {
1696                                         $post .= '[h3]' . $item['title'] . "[/h3]\n";
1697                                 }
1698
1699                                 $post .= $item['body'];
1700                                 $post .= "[/share]";
1701                         }
1702                         $_REQUEST['body'] = $post;
1703                         $_REQUEST['profile_uid'] = $uid;
1704                         $_REQUEST['api_source'] = true;
1705
1706                         if (empty($_REQUEST['source'])) {
1707                                 $_REQUEST['source'] = BaseApi::getCurrentApplication()['name'] ?: 'API';
1708                         }
1709
1710                         $item_id = item_post(DI::app());
1711                 }
1712         } else {
1713                 throw new ForbiddenException();
1714         }
1715
1716         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1717
1718         // output the post that we just posted.
1719         $status_info = DI::twitterStatus()->createFromItemId($item_id, $include_entities)->toArray();
1720         return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
1721 }
1722
1723 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1724
1725 /**
1726  * Destroys a specific status.
1727  *
1728  * @param string $type Return type (atom, rss, xml, json)
1729  *
1730  * @return array|string
1731  * @throws BadRequestException
1732  * @throws ForbiddenException
1733  * @throws ImagickException
1734  * @throws InternalServerErrorException
1735  * @throws UnauthorizedException
1736  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1737  */
1738 function api_statuses_destroy($type)
1739 {
1740         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1741         $uid = BaseApi::getCurrentUserID();
1742
1743         // params
1744         $id = intval(DI::args()->getArgv()[3] ?? 0);
1745
1746         if ($id == 0) {
1747                 $id = intval($_REQUEST['id'] ?? 0);
1748         }
1749
1750         // Hotot workaround
1751         if ($id == 0) {
1752                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1753         }
1754
1755         logger::notice('API: api_statuses_destroy: ' . $id);
1756
1757         $ret = api_statuses_show($type);
1758
1759         Item::deleteForUser(['id' => $id], $uid);
1760
1761         return $ret;
1762 }
1763
1764 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1765
1766 /**
1767  * Returns the most recent mentions.
1768  *
1769  * @param string $type Return type (atom, rss, xml, json)
1770  *
1771  * @return array|string
1772  * @throws BadRequestException
1773  * @throws ForbiddenException
1774  * @throws ImagickException
1775  * @throws InternalServerErrorException
1776  * @throws UnauthorizedException
1777  * @see http://developer.twitter.com/doc/get/statuses/mentions
1778  */
1779 function api_statuses_mentions($type)
1780 {
1781         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1782         $uid = BaseApi::getCurrentUserID();
1783
1784         unset($_REQUEST['user_id']);
1785         unset($_GET['user_id']);
1786
1787         unset($_REQUEST['screen_name']);
1788         unset($_GET['screen_name']);
1789
1790         // get last network messages
1791
1792         // params
1793         $since_id = intval($_REQUEST['since_id'] ?? 0);
1794         $max_id   = intval($_REQUEST['max_id']   ?? 0);
1795         $count    = intval($_REQUEST['count']    ?? 20);
1796         $page     = intval($_REQUEST['page']     ?? 1);
1797
1798         $start = max(0, ($page - 1) * $count);
1799
1800         $query = "`gravity` IN (?, ?) AND `uri-id` IN
1801                 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1802                 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1803
1804         $condition = [
1805                 GRAVITY_PARENT, GRAVITY_COMMENT,
1806                 $uid,
1807                 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1808                 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1809                 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1810                 $uid, $since_id,
1811         ];
1812
1813         if ($max_id > 0) {
1814                 $query .= " AND `id` <= ?";
1815                 $condition[] = $max_id;
1816         }
1817
1818         array_unshift($condition, $query);
1819
1820         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1821         $statuses = Post::selectForUser($uid, [], $condition, $params);
1822
1823         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1824
1825         $ret = [];
1826         while ($status = DBA::fetch($statuses)) {
1827                 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1828         }
1829         DBA::close($statuses);
1830
1831         return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1832 }
1833
1834 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1835 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1836
1837 /**
1838  * Returns the most recent statuses posted by the user.
1839  *
1840  * @param string $type Either "json" or "xml"
1841  * @return string|array
1842  * @throws BadRequestException
1843  * @throws ForbiddenException
1844  * @throws ImagickException
1845  * @throws InternalServerErrorException
1846  * @throws UnauthorizedException
1847  * @see   https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1848  */
1849 function api_statuses_user_timeline($type)
1850 {
1851         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1852         $uid = BaseApi::getCurrentUserID();
1853
1854         Logger::info('api_statuses_user_timeline', ['api_user' => $uid, '_REQUEST' => $_REQUEST]);
1855
1856         $cid             = BaseApi::getContactIDForSearchterm($_REQUEST['screen_name'] ?? '', $_REQUEST['user_id'] ?? 0, $uid);
1857         $since_id        = $_REQUEST['since_id'] ?? 0;
1858         $max_id          = $_REQUEST['max_id'] ?? 0;
1859         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1860         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1861
1862         // pagination
1863         $count = $_REQUEST['count'] ?? 20;
1864         $page  = $_REQUEST['page'] ?? 1;
1865
1866         $start = max(0, ($page - 1) * $count);
1867
1868         $condition = ["(`uid` = ? OR (`uid` = ? AND NOT `global`)) AND `gravity` IN (?, ?) AND `id` > ? AND `author-id` = ?",
1869                 0, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $cid];
1870
1871         if ($exclude_replies) {
1872                 $condition[0] .= ' AND `gravity` = ?';
1873                 $condition[] = GRAVITY_PARENT;
1874         }
1875
1876         if ($conversation_id > 0) {
1877                 $condition[0] .= " AND `parent` = ?";
1878                 $condition[] = $conversation_id;
1879         }
1880
1881         if ($max_id > 0) {
1882                 $condition[0] .= " AND `id` <= ?";
1883                 $condition[] = $max_id;
1884         }
1885         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1886         $statuses = Post::selectForUser($uid, [], $condition, $params);
1887
1888         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1889
1890         $ret = [];
1891         while ($status = DBA::fetch($statuses)) {
1892                 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
1893         }
1894         DBA::close($statuses);
1895
1896         return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1897 }
1898
1899 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1900
1901 /**
1902  * Star/unstar an item.
1903  * param: id : id of the item
1904  *
1905  * @param string $type Return type (atom, rss, xml, json)
1906  *
1907  * @return array|string
1908  * @throws BadRequestException
1909  * @throws ForbiddenException
1910  * @throws ImagickException
1911  * @throws InternalServerErrorException
1912  * @throws UnauthorizedException
1913  * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1914  */
1915 function api_favorites_create_destroy($type)
1916 {
1917         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1918         $uid = BaseApi::getCurrentUserID();
1919
1920         // for versioned api.
1921         /// @TODO We need a better global soluton
1922         $action_argv_id = 2;
1923         if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1924                 $action_argv_id = 3;
1925         }
1926
1927         if (DI::args()->getArgc() <= $action_argv_id) {
1928                 throw new BadRequestException("Invalid request.");
1929         }
1930         $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1931         if (DI::args()->getArgc() == $action_argv_id + 2) {
1932                 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1933         } else {
1934                 $itemid = intval($_REQUEST['id'] ?? 0);
1935         }
1936
1937         $item = Post::selectFirstForUser($uid, [], ['id' => $itemid, 'uid' => $uid]);
1938
1939         if (!DBA::isResult($item)) {
1940                 throw new BadRequestException("Invalid item.");
1941         }
1942
1943         switch ($action) {
1944                 case "create":
1945                         $item['starred'] = 1;
1946                         break;
1947                 case "destroy":
1948                         $item['starred'] = 0;
1949                         break;
1950                 default:
1951                         throw new BadRequestException("Invalid action ".$action);
1952         }
1953
1954         $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1955
1956         if ($r === false) {
1957                 throw new InternalServerErrorException("DB error");
1958         }
1959
1960         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
1961
1962         $ret = DI::twitterStatus()->createFromUriId($item['uri-id'], $item['uid'], $include_entities)->toArray();
1963
1964         return DI::apiResponse()->formatData("status", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1965 }
1966
1967 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1968 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1969
1970 /**
1971  * Returns the most recent favorite statuses.
1972  *
1973  * @param string $type Return type (atom, rss, xml, json)
1974  *
1975  * @return string|array
1976  * @throws BadRequestException
1977  * @throws ForbiddenException
1978  * @throws ImagickException
1979  * @throws InternalServerErrorException
1980  * @throws UnauthorizedException
1981  */
1982 function api_favorites($type)
1983 {
1984         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1985         $uid = BaseApi::getCurrentUserID();
1986
1987         // in friendica starred item are private
1988         // return favorites only for self
1989         Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites']);
1990
1991         // params
1992         $since_id = $_REQUEST['since_id'] ?? 0;
1993         $max_id = $_REQUEST['max_id'] ?? 0;
1994         $count = $_GET['count'] ?? 20;
1995         $page = $_REQUEST['page'] ?? 1;
1996
1997         $start = max(0, ($page - 1) * $count);
1998
1999         $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2000                 $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2001
2002         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2003
2004         if ($max_id > 0) {
2005                 $condition[0] .= " AND `id` <= ?";
2006                 $condition[] = $max_id;
2007         }
2008
2009         $statuses = Post::selectForUser($uid, [], $condition, $params);
2010
2011         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
2012
2013         $ret = [];
2014         while ($status = DBA::fetch($statuses)) {
2015                 $ret[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
2016         }
2017         DBA::close($statuses);
2018
2019         return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
2020 }
2021
2022 api_register_func('api/favorites', 'api_favorites', true);
2023
2024 /**
2025  * Returns all lists the user subscribes to.
2026  *
2027  * @param string $type Return type (atom, rss, xml, json)
2028  *
2029  * @return array|string
2030  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2031  */
2032 function api_lists_list($type)
2033 {
2034         $ret = [];
2035         /// @TODO $ret is not filled here?
2036         return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2037 }
2038
2039 api_register_func('api/lists/list', 'api_lists_list', true);
2040 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2041
2042 /**
2043  * Returns all groups the user owns.
2044  *
2045  * @param string $type Return type (atom, rss, xml, json)
2046  *
2047  * @return array|string
2048  * @throws BadRequestException
2049  * @throws ForbiddenException
2050  * @throws ImagickException
2051  * @throws InternalServerErrorException
2052  * @throws UnauthorizedException
2053  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2054  */
2055 function api_lists_ownerships($type)
2056 {
2057         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2058         $uid = BaseApi::getCurrentUserID();
2059
2060         // params
2061         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2062
2063         $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2064
2065         // loop through all groups
2066         $lists = [];
2067         foreach ($groups as $group) {
2068                 if ($group['visible']) {
2069                         $mode = 'public';
2070                 } else {
2071                         $mode = 'private';
2072                 }
2073                 $lists[] = [
2074                         'name' => $group['name'],
2075                         'id' => intval($group['id']),
2076                         'id_str' => (string) $group['id'],
2077                         'user' => $user_info,
2078                         'mode' => $mode
2079                 ];
2080         }
2081         return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2082 }
2083
2084 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2085
2086 /**
2087  * Returns recent statuses from users in the specified group.
2088  *
2089  * @param string $type Return type (atom, rss, xml, json)
2090  *
2091  * @return array|string
2092  * @throws BadRequestException
2093  * @throws ForbiddenException
2094  * @throws ImagickException
2095  * @throws InternalServerErrorException
2096  * @throws UnauthorizedException
2097  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2098  */
2099 function api_lists_statuses($type)
2100 {
2101         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2102         $uid = BaseApi::getCurrentUserID();
2103
2104         unset($_REQUEST['user_id']);
2105         unset($_GET['user_id']);
2106
2107         unset($_REQUEST['screen_name']);
2108         unset($_GET['screen_name']);
2109
2110         if (empty($_REQUEST['list_id'])) {
2111                 throw new BadRequestException('list_id not specified');
2112         }
2113
2114         // params
2115         $count = $_REQUEST['count'] ?? 20;
2116         $page = $_REQUEST['page'] ?? 1;
2117         $since_id = $_REQUEST['since_id'] ?? 0;
2118         $max_id = $_REQUEST['max_id'] ?? 0;
2119         $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2120         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2121
2122         $start = max(0, ($page - 1) * $count);
2123
2124         $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2125         $gids = array_column($groups, 'contact-id');
2126         $condition = ['uid' => $uid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2127         $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2128
2129         if ($max_id > 0) {
2130                 $condition[0] .= " AND `id` <= ?";
2131                 $condition[] = $max_id;
2132         }
2133         if ($exclude_replies > 0) {
2134                 $condition[0] .= ' AND `gravity` = ?';
2135                 $condition[] = GRAVITY_PARENT;
2136         }
2137         if ($conversation_id > 0) {
2138                 $condition[0] .= " AND `parent` = ?";
2139                 $condition[] = $conversation_id;
2140         }
2141
2142         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2143         $statuses = Post::selectForUser($uid, [], $condition, $params);
2144
2145         $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
2146
2147         $items = [];
2148         while ($status = DBA::fetch($statuses)) {
2149                 $items[] = DI::twitterStatus()->createFromUriId($status['uri-id'], $status['uid'], $include_entities)->toArray();
2150         }
2151         DBA::close($statuses);
2152
2153         return DI::apiResponse()->formatData("statuses", $type, ['status' => $items], Contact::getPublicIdByUserId($uid));
2154 }
2155
2156 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2157
2158 /**
2159  * Returns either the friends of the follower list
2160  *
2161  * Considers friends and followers lists to be private and won't return
2162  * anything if any user_id parameter is passed.
2163  *
2164  * @param string $qtype Either "friends" or "followers"
2165  * @return boolean|array
2166  * @throws BadRequestException
2167  * @throws ForbiddenException
2168  * @throws ImagickException
2169  * @throws InternalServerErrorException
2170  * @throws UnauthorizedException
2171  */
2172 function api_statuses_f($qtype)
2173 {
2174         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2175         $uid = BaseApi::getCurrentUserID();
2176
2177         // pagination
2178         $count = $_GET['count'] ?? 20;
2179         $page = $_GET['page'] ?? 1;
2180
2181         $start = max(0, ($page - 1) * $count);
2182
2183         if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2184                 /* this is to stop Hotot to load friends multiple times
2185                 *  I'm not sure if I'm missing return something or
2186                 *  is a bug in hotot. Workaround, meantime
2187                 */
2188
2189                 /*$ret=Array();
2190                 return array('$users' => $ret);*/
2191                 return false;
2192         }
2193
2194         $sql_extra = '';
2195         if ($qtype == 'friends') {
2196                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2197         } elseif ($qtype == 'followers') {
2198                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2199         }
2200
2201         if ($qtype == 'blocks') {
2202                 $sql_filter = 'AND `blocked` AND NOT `pending`';
2203         } elseif ($qtype == 'incoming') {
2204                 $sql_filter = 'AND `pending`';
2205         } else {
2206                 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2207         }
2208
2209         // @todo This query most likely can be replaced with a Contact::select...
2210         $r = DBA::toArray(DBA::p(
2211                 "SELECT `id`
2212                 FROM `contact`
2213                 WHERE `uid` = ?
2214                 AND NOT `self`
2215                 $sql_filter
2216                 $sql_extra
2217                 ORDER BY `nick`
2218                 LIMIT ?, ?",
2219                 $uid,
2220                 $start,
2221                 $count
2222         ));
2223
2224         $ret = [];
2225         foreach ($r as $cid) {
2226                 $user = DI::twitterUser()->createFromContactId($cid['id'], $uid, false)->toArray();
2227                 // "uid" is only needed for some internal stuff, so remove it from here
2228                 unset($user['uid']);
2229
2230                 if ($user) {
2231                         $ret[] = $user;
2232                 }
2233         }
2234
2235         return ['user' => $ret];
2236 }
2237
2238 /**
2239  * Returns the list of friends of the provided user
2240  *
2241  * @deprecated By Twitter API in favor of friends/list
2242  *
2243  * @param string $type Either "json" or "xml"
2244  * @return boolean|string|array
2245  * @throws BadRequestException
2246  * @throws ForbiddenException
2247  */
2248 function api_statuses_friends($type)
2249 {
2250         $data =  api_statuses_f("friends");
2251         if ($data === false) {
2252                 return false;
2253         }
2254         return DI::apiResponse()->formatData("users", $type, $data);
2255 }
2256
2257 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2258
2259 /**
2260  * Returns the list of followers of the provided user
2261  *
2262  * @deprecated By Twitter API in favor of friends/list
2263  *
2264  * @param string $type Either "json" or "xml"
2265  * @return boolean|string|array
2266  * @throws BadRequestException
2267  * @throws ForbiddenException
2268  */
2269 function api_statuses_followers($type)
2270 {
2271         $data = api_statuses_f("followers");
2272         if ($data === false) {
2273                 return false;
2274         }
2275         return DI::apiResponse()->formatData("users", $type, $data);
2276 }
2277
2278 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2279
2280 /**
2281  * Returns the list of blocked users
2282  *
2283  * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
2284  *
2285  * @param string $type Either "json" or "xml"
2286  *
2287  * @return boolean|string|array
2288  * @throws BadRequestException
2289  * @throws ForbiddenException
2290  */
2291 function api_blocks_list($type)
2292 {
2293         $data =  api_statuses_f('blocks');
2294         if ($data === false) {
2295                 return false;
2296         }
2297         return DI::apiResponse()->formatData("users", $type, $data);
2298 }
2299
2300 api_register_func('api/blocks/list', 'api_blocks_list', true);
2301
2302 /**
2303  * Returns the list of pending users IDs
2304  *
2305  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
2306  *
2307  * @param string $type Either "json" or "xml"
2308  *
2309  * @return boolean|string|array
2310  * @throws BadRequestException
2311  * @throws ForbiddenException
2312  */
2313 function api_friendships_incoming($type)
2314 {
2315         $data =  api_statuses_f('incoming');
2316         if ($data === false) {
2317                 return false;
2318         }
2319
2320         $ids = [];
2321         foreach ($data['user'] as $user) {
2322                 $ids[] = $user['id'];
2323         }
2324
2325         return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
2326 }
2327
2328 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
2329
2330 /**
2331  * Sends a new direct message.
2332  *
2333  * @param string $type Return type (atom, rss, xml, json)
2334  *
2335  * @return array|string
2336  * @throws BadRequestException
2337  * @throws ForbiddenException
2338  * @throws ImagickException
2339  * @throws InternalServerErrorException
2340  * @throws NotFoundException
2341  * @throws UnauthorizedException
2342  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
2343  */
2344 function api_direct_messages_new($type)
2345 {
2346         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2347         $uid = BaseApi::getCurrentUserID();
2348
2349         if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
2350                 return;
2351         }
2352
2353         $sender = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2354
2355         $cid = BaseApi::getContactIDForSearchterm($_POST['screen_name'] ?? '', $_POST['user_id'] ?? 0, $uid);
2356         if (empty($cid)) {
2357                 throw new NotFoundException('Recipient not found');
2358         }
2359
2360         $replyto = '';
2361         if (!empty($_REQUEST['replyto'])) {
2362                 $mail    = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
2363                 $replyto = $mail['parent-uri'];
2364                 $sub     = $mail['title'];
2365         } else {
2366                 if (!empty($_REQUEST['title'])) {
2367                         $sub = $_REQUEST['title'];
2368                 } else {
2369                         $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
2370                 }
2371         }
2372
2373         $cdata = Contact::getPublicAndUserContactID($cid, $uid);
2374
2375         $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
2376
2377         if ($id > -1) {
2378                 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
2379                 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid, true)->toArray(), $sender);
2380         } else {
2381                 $ret = ["error" => $id];
2382         }
2383
2384         return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2385 }
2386
2387 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
2388
2389 /**
2390  * delete a direct_message from mail table through api
2391  *
2392  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2393  * @return string|array
2394  * @throws BadRequestException
2395  * @throws ForbiddenException
2396  * @throws ImagickException
2397  * @throws InternalServerErrorException
2398  * @throws UnauthorizedException
2399  * @see   https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
2400  */
2401 function api_direct_messages_destroy($type)
2402 {
2403         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2404         $uid = BaseApi::getCurrentUserID();
2405
2406         //required
2407         $id = $_REQUEST['id'] ?? 0;
2408         // optional
2409         $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
2410         $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
2411         /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
2412
2413         // error if no id or parenturi specified (for clients posting parent-uri as well)
2414         if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
2415                 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
2416                 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2417         }
2418
2419         // BadRequestException if no id specified (for clients using Twitter API)
2420         if ($id == 0) {
2421                 throw new BadRequestException('Message id not specified');
2422         }
2423
2424         // add parent-uri to sql command if specified by calling app
2425         $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
2426
2427         // error message if specified id is not in database
2428         if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
2429                 if ($verbose == "true") {
2430                         $answer = ['result' => 'error', 'message' => 'message id not in database'];
2431                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2432                 }
2433                 /// @todo BadRequestException ok for Twitter API clients?
2434                 throw new BadRequestException('message id not in database');
2435         }
2436
2437         // delete message
2438         $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
2439
2440         if ($verbose == "true") {
2441                 if ($result) {
2442                         // return success
2443                         $answer = ['result' => 'ok', 'message' => 'message deleted'];
2444                         return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
2445                 } else {
2446                         $answer = ['result' => 'error', 'message' => 'unknown error'];
2447                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2448                 }
2449         }
2450         /// @todo return JSON data like Twitter API not yet implemented
2451 }
2452
2453 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2454
2455 /**
2456  * Unfollow Contact
2457  *
2458  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2459  * @return string|array
2460  * @throws HTTPException\BadRequestException
2461  * @throws HTTPException\ExpectationFailedException
2462  * @throws HTTPException\ForbiddenException
2463  * @throws HTTPException\InternalServerErrorException
2464  * @throws HTTPException\NotFoundException
2465  * @see   https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
2466  */
2467 function api_friendships_destroy($type)
2468 {
2469         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2470         $uid = BaseApi::getCurrentUserID();
2471
2472         $owner = User::getOwnerDataById($uid);
2473         if (!$owner) {
2474                 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
2475                 throw new HTTPException\NotFoundException('Error Processing Request');
2476         }
2477
2478         $contact_id = $_REQUEST['user_id'] ?? 0;
2479
2480         if (empty($contact_id)) {
2481                 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
2482                 throw new HTTPException\BadRequestException('no user_id specified');
2483         }
2484
2485         // Get Contact by given id
2486         $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
2487
2488         if(!DBA::isResult($contact)) {
2489                 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
2490                 throw new HTTPException\NotFoundException('no contact found to given ID');
2491         }
2492
2493         $url = $contact['url'];
2494
2495         $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
2496                         $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
2497                         Strings::normaliseLink($url), $url];
2498         $contact = DBA::selectFirst('contact', [], $condition);
2499
2500         if (!DBA::isResult($contact)) {
2501                 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
2502                 throw new HTTPException\NotFoundException('Not following Contact');
2503         }
2504
2505         try {
2506                 $result = Contact::terminateFriendship($owner, $contact);
2507
2508                 if ($result === null) {
2509                         Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
2510                         throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
2511                 }
2512
2513                 if ($result === false) {
2514                         throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
2515                 }
2516         } catch (Exception $e) {
2517                 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
2518                 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
2519         }
2520
2521         // "uid" is only needed for some internal stuff, so remove it from here
2522         unset($contact['uid']);
2523
2524         // Set screen_name since Twidere requests it
2525         $contact['screen_name'] = $contact['nick'];
2526
2527         return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
2528 }
2529
2530 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
2531
2532 /**
2533  *
2534  * @param string $type Return type (atom, rss, xml, json)
2535  * @param string $box
2536  * @param string $verbose
2537  *
2538  * @return array|string
2539  * @throws BadRequestException
2540  * @throws ForbiddenException
2541  * @throws ImagickException
2542  * @throws InternalServerErrorException
2543  * @throws UnauthorizedException
2544  */
2545 function api_direct_messages_box($type, $box, $verbose)
2546 {
2547         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2548         $uid = BaseApi::getCurrentUserID();
2549
2550         // params
2551         $count = $_GET['count'] ?? 20;
2552         $page = $_REQUEST['page'] ?? 1;
2553
2554         $since_id = $_REQUEST['since_id'] ?? 0;
2555         $max_id = $_REQUEST['max_id'] ?? 0;
2556
2557         $user_id = $_REQUEST['user_id'] ?? '';
2558         $screen_name = $_REQUEST['screen_name'] ?? '';
2559
2560         //  caller user info
2561         unset($_REQUEST['user_id']);
2562         unset($_GET['user_id']);
2563
2564         unset($_REQUEST['screen_name']);
2565         unset($_GET['screen_name']);
2566
2567         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
2568
2569         $profile_url = $user_info["url"];
2570
2571         // pagination
2572         $start = max(0, ($page - 1) * $count);
2573
2574         $sql_extra = "";
2575
2576         // filters
2577         if ($box=="sentbox") {
2578                 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
2579         } elseif ($box == "conversation") {
2580                 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '')  . "'";
2581         } elseif ($box == "all") {
2582                 $sql_extra = "true";
2583         } elseif ($box == "inbox") {
2584                 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
2585         }
2586
2587         if ($max_id > 0) {
2588                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
2589         }
2590
2591         if ($user_id != "") {
2592                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2593         } elseif ($screen_name !="") {
2594                 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
2595         }
2596
2597         $r = DBA::toArray(DBA::p(
2598                 "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 ?,?",
2599                 $uid,
2600                 $since_id,
2601                 $start,
2602                 $count
2603         ));
2604         if ($verbose == "true" && !DBA::isResult($r)) {
2605                 $answer = ['result' => 'error', 'message' => 'no mails available'];
2606                 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
2607         }
2608
2609         $ret = [];
2610         foreach ($r as $item) {
2611                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
2612                         $recipient = $user_info;
2613                         $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2614                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
2615                         $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
2616                         $sender = $user_info;
2617                 }
2618
2619                 if (isset($recipient) && isset($sender)) {
2620                         $ret[] = api_format_messages($item, $recipient, $sender);
2621                 }
2622         }
2623
2624         return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2625 }
2626
2627 /**
2628  * Returns the most recent direct messages sent by the user.
2629  *
2630  * @param string $type Return type (atom, rss, xml, json)
2631  *
2632  * @return array|string
2633  * @throws BadRequestException
2634  * @throws ForbiddenException
2635  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
2636  */
2637 function api_direct_messages_sentbox($type)
2638 {
2639         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2640         return api_direct_messages_box($type, "sentbox", $verbose);
2641 }
2642
2643 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
2644
2645 /**
2646  * Returns the most recent direct messages sent to the user.
2647  *
2648  * @param string $type Return type (atom, rss, xml, json)
2649  *
2650  * @return array|string
2651  * @throws BadRequestException
2652  * @throws ForbiddenException
2653  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
2654  */
2655 function api_direct_messages_inbox($type)
2656 {
2657         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2658         return api_direct_messages_box($type, "inbox", $verbose);
2659 }
2660
2661 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
2662
2663 /**
2664  *
2665  * @param string $type Return type (atom, rss, xml, json)
2666  *
2667  * @return array|string
2668  * @throws BadRequestException
2669  * @throws ForbiddenException
2670  */
2671 function api_direct_messages_all($type)
2672 {
2673         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2674         return api_direct_messages_box($type, "all", $verbose);
2675 }
2676
2677 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
2678
2679 /**
2680  *
2681  * @param string $type Return type (atom, rss, xml, json)
2682  *
2683  * @return array|string
2684  * @throws BadRequestException
2685  * @throws ForbiddenException
2686  */
2687 function api_direct_messages_conversation($type)
2688 {
2689         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2690         return api_direct_messages_box($type, "conversation", $verbose);
2691 }
2692
2693 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
2694
2695 /**
2696  * list all photos of the authenticated user
2697  *
2698  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2699  * @return string|array
2700  * @throws ForbiddenException
2701  * @throws InternalServerErrorException
2702  */
2703 function api_fr_photos_list($type)
2704 {
2705         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2706         $uid = BaseApi::getCurrentUserID();
2707
2708         $r = DBA::toArray(DBA::p(
2709                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
2710                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
2711                 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
2712                 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
2713         ));
2714         $typetoext = [
2715                 'image/jpeg' => 'jpg',
2716                 'image/png' => 'png',
2717                 'image/gif' => 'gif'
2718         ];
2719         $data = ['photo'=>[]];
2720         if (DBA::isResult($r)) {
2721                 foreach ($r as $rr) {
2722                         $photo = [];
2723                         $photo['id'] = $rr['resource-id'];
2724                         $photo['album'] = $rr['album'];
2725                         $photo['filename'] = $rr['filename'];
2726                         $photo['type'] = $rr['type'];
2727                         $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
2728                         $photo['created'] = $rr['created'];
2729                         $photo['edited'] = $rr['edited'];
2730                         $photo['desc'] = $rr['desc'];
2731
2732                         if ($type == "xml") {
2733                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
2734                         } else {
2735                                 $photo['thumb'] = $thumb;
2736                                 $data['photo'][] = $photo;
2737                         }
2738                 }
2739         }
2740         return DI::apiResponse()->formatData("photos", $type, $data);
2741 }
2742
2743 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2744
2745 /**
2746  * upload a new photo or change an existing photo
2747  *
2748  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2749  * @return string|array
2750  * @throws BadRequestException
2751  * @throws ForbiddenException
2752  * @throws ImagickException
2753  * @throws InternalServerErrorException
2754  * @throws NotFoundException
2755  */
2756 function api_fr_photo_create_update($type)
2757 {
2758         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2759         $uid = BaseApi::getCurrentUserID();
2760
2761         // input params
2762         $photo_id  = $_REQUEST['photo_id']  ?? null;
2763         $desc      = $_REQUEST['desc']      ?? null;
2764         $album     = $_REQUEST['album']     ?? null;
2765         $album_new = $_REQUEST['album_new'] ?? null;
2766         $allow_cid = $_REQUEST['allow_cid'] ?? null;
2767         $deny_cid  = $_REQUEST['deny_cid' ] ?? null;
2768         $allow_gid = $_REQUEST['allow_gid'] ?? null;
2769         $deny_gid  = $_REQUEST['deny_gid' ] ?? null;
2770         $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
2771
2772         // do several checks on input parameters
2773         // we do not allow calls without album string
2774         if ($album == null) {
2775                 throw new BadRequestException("no albumname specified");
2776         }
2777         // if photo_id == null --> we are uploading a new photo
2778         if ($photo_id == null) {
2779                 $mode = "create";
2780
2781                 // error if no media posted in create-mode
2782                 if (empty($_FILES['media'])) {
2783                         // Output error
2784                         throw new BadRequestException("no media data submitted");
2785                 }
2786
2787                 // album_new will be ignored in create-mode
2788                 $album_new = "";
2789         } else {
2790                 $mode = "update";
2791
2792                 // check if photo is existing in databasei
2793                 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
2794                         throw new BadRequestException("photo not available");
2795                 }
2796         }
2797
2798         // checks on acl strings provided by clients
2799         $acl_input_error = false;
2800         $acl_input_error |= check_acl_input($allow_cid, $uid);
2801         $acl_input_error |= check_acl_input($deny_cid, $uid);
2802         $acl_input_error |= check_acl_input($allow_gid, $uid);
2803         $acl_input_error |= check_acl_input($deny_gid, $uid);
2804         if ($acl_input_error) {
2805                 throw new BadRequestException("acl data invalid");
2806         }
2807         // now let's upload the new media in create-mode
2808         if ($mode == "create") {
2809                 $media = $_FILES['media'];
2810                 $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);
2811
2812                 // return success of updating or error message
2813                 if (!is_null($data)) {
2814                         return DI::apiResponse()->formatData("photo_create", $type, $data);
2815                 } else {
2816                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
2817                 }
2818         }
2819
2820         // now let's do the changes in update-mode
2821         if ($mode == "update") {
2822                 $updated_fields = [];
2823
2824                 if (!is_null($desc)) {
2825                         $updated_fields['desc'] = $desc;
2826                 }
2827
2828                 if (!is_null($album_new)) {
2829                         $updated_fields['album'] = $album_new;
2830                 }
2831
2832                 if (!is_null($allow_cid)) {
2833                         $allow_cid = trim($allow_cid);
2834                         $updated_fields['allow_cid'] = $allow_cid;
2835                 }
2836
2837                 if (!is_null($deny_cid)) {
2838                         $deny_cid = trim($deny_cid);
2839                         $updated_fields['deny_cid'] = $deny_cid;
2840                 }
2841
2842                 if (!is_null($allow_gid)) {
2843                         $allow_gid = trim($allow_gid);
2844                         $updated_fields['allow_gid'] = $allow_gid;
2845                 }
2846
2847                 if (!is_null($deny_gid)) {
2848                         $deny_gid = trim($deny_gid);
2849                         $updated_fields['deny_gid'] = $deny_gid;
2850                 }
2851
2852                 $result = false;
2853                 if (count($updated_fields) > 0) {
2854                         $nothingtodo = false;
2855                         $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
2856                 } else {
2857                         $nothingtodo = true;
2858                 }
2859
2860                 if (!empty($_FILES['media'])) {
2861                         $nothingtodo = false;
2862                         $media = $_FILES['media'];
2863                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
2864                         if (!is_null($data)) {
2865                                 return DI::apiResponse()->formatData("photo_update", $type, $data);
2866                         }
2867                 }
2868
2869                 // return success of updating or error message
2870                 if ($result) {
2871                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
2872                         return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
2873                 } else {
2874                         if ($nothingtodo) {
2875                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
2876                                 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
2877                         }
2878                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
2879                 }
2880         }
2881         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
2882 }
2883
2884 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
2885 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
2886
2887 /**
2888  * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
2889  *
2890  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2891  * @return string|array
2892  * @throws BadRequestException
2893  * @throws ForbiddenException
2894  * @throws InternalServerErrorException
2895  * @throws NotFoundException
2896  */
2897 function api_fr_photo_detail($type)
2898 {
2899         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2900         $uid = BaseApi::getCurrentUserID();
2901
2902         if (empty($_REQUEST['photo_id'])) {
2903                 throw new BadRequestException("No photo id.");
2904         }
2905
2906         $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
2907         $photo_id = $_REQUEST['photo_id'];
2908
2909         // prepare json/xml output with data from database for the requested photo
2910         $data = prepare_photo_data($type, $scale, $photo_id, $uid);
2911
2912         return DI::apiResponse()->formatData("photo_detail", $type, $data);
2913 }
2914
2915 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2916
2917 /**
2918  * updates the profile image for the user (either a specified profile or the default profile)
2919  *
2920  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2921  *
2922  * @return string|array
2923  * @throws BadRequestException
2924  * @throws ForbiddenException
2925  * @throws ImagickException
2926  * @throws InternalServerErrorException
2927  * @throws NotFoundException
2928  * @see   https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
2929  */
2930 function api_account_update_profile_image($type)
2931 {
2932         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2933         $uid = BaseApi::getCurrentUserID();
2934
2935         // input params
2936         $profile_id = $_REQUEST['profile_id'] ?? 0;
2937
2938         // error if image data is missing
2939         if (empty($_FILES['image'])) {
2940                 throw new BadRequestException("no media data submitted");
2941         }
2942
2943         // check if specified profile id is valid
2944         if ($profile_id != 0) {
2945                 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
2946                 // error message if specified profile id is not in database
2947                 if (!DBA::isResult($profile)) {
2948                         throw new BadRequestException("profile_id not available");
2949                 }
2950                 $is_default_profile = $profile['is-default'];
2951         } else {
2952                 $is_default_profile = 1;
2953         }
2954
2955         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
2956         $media = null;
2957         if (!empty($_FILES['image'])) {
2958                 $media = $_FILES['image'];
2959         } elseif (!empty($_FILES['media'])) {
2960                 $media = $_FILES['media'];
2961         }
2962         // save new profile image
2963         $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
2964
2965         // get filetype
2966         if (is_array($media['type'])) {
2967                 $filetype = $media['type'][0];
2968         } else {
2969                 $filetype = $media['type'];
2970         }
2971         if ($filetype == "image/jpeg") {
2972                 $fileext = "jpg";
2973         } elseif ($filetype == "image/png") {
2974                 $fileext = "png";
2975         } else {
2976                 throw new InternalServerErrorException('Unsupported filetype');
2977         }
2978
2979         // change specified profile or all profiles to the new resource-id
2980         if ($is_default_profile) {
2981                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
2982                 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
2983         } else {
2984                 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
2985                         'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
2986                 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
2987         }
2988
2989         Contact::updateSelfFromUserID($uid, true);
2990
2991         // Update global directory in background
2992         Profile::publishUpdate($uid);
2993
2994         // output for client
2995         if ($data) {
2996                 return api_account_verify_credentials($type);
2997         } else {
2998                 // SaveMediaToDatabase failed for some reason
2999                 throw new InternalServerErrorException("image upload failed");
3000         }
3001 }
3002
3003 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3004
3005 /**
3006  * Update user profile
3007  *
3008  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3009  *
3010  * @return array|string
3011  * @throws BadRequestException
3012  * @throws ForbiddenException
3013  * @throws ImagickException
3014  * @throws InternalServerErrorException
3015  * @throws UnauthorizedException
3016  */
3017 function api_account_update_profile($type)
3018 {
3019         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3020         $uid = BaseApi::getCurrentUserID();
3021
3022         $api_user = DI::twitterUser()->createFromUserId($uid, true)->toArray();
3023
3024         if (!empty($_POST['name'])) {
3025                 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $uid]);
3026                 DBA::update('user', ['username' => $_POST['name']], ['uid' => $uid]);
3027                 Contact::update(['name' => $_POST['name']], ['uid' => $uid, 'self' => 1]);
3028                 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3029         }
3030
3031         if (isset($_POST['description'])) {
3032                 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $uid]);
3033                 Contact::update(['about' => $_POST['description']], ['uid' => $uid, 'self' => 1]);
3034                 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3035         }
3036
3037         Profile::publishUpdate($uid);
3038
3039         return api_account_verify_credentials($type);
3040 }
3041
3042 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3043
3044 /**
3045  * Return all or a specified group of the user with the containing contacts.
3046  *
3047  * @param string $type Return type (atom, rss, xml, json)
3048  *
3049  * @return array|string
3050  * @throws BadRequestException
3051  * @throws ForbiddenException
3052  * @throws ImagickException
3053  * @throws InternalServerErrorException
3054  * @throws UnauthorizedException
3055  */
3056 function api_friendica_group_show($type)
3057 {
3058         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3059         $uid = BaseApi::getCurrentUserID();
3060
3061         // params
3062         $gid = $_REQUEST['gid'] ?? 0;
3063
3064         // get data of the specified group id or all groups if not specified
3065         if ($gid != 0) {
3066                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
3067
3068                 // error message if specified gid is not in database
3069                 if (!DBA::isResult($groups)) {
3070                         throw new BadRequestException("gid not available");
3071                 }
3072         } else {
3073                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
3074         }
3075
3076         // loop through all groups and retrieve all members for adding data in the user array
3077         $grps = [];
3078         foreach ($groups as $rr) {
3079                 $members = Contact\Group::getById($rr['id']);
3080                 $users = [];
3081
3082                 if ($type == "xml") {
3083                         $user_element = "users";
3084                         $k = 0;
3085                         foreach ($members as $member) {
3086                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
3087                                 $users[$k++.":user"] = $user;
3088                         }
3089                 } else {
3090                         $user_element = "user";
3091                         foreach ($members as $member) {
3092                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid, true)->toArray();
3093                                 $users[] = $user;
3094                         }
3095                 }
3096                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
3097         }
3098         return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
3099 }
3100
3101 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3102
3103 /**
3104  * Delete a group.
3105  *
3106  * @param string $type Return type (atom, rss, xml, json)
3107  *
3108  * @return array|string
3109  * @throws BadRequestException
3110  * @throws ForbiddenException
3111  * @throws ImagickException
3112  * @throws InternalServerErrorException
3113  * @throws UnauthorizedException
3114  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
3115  */
3116 function api_lists_destroy($type)
3117 {
3118         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3119         $uid = BaseApi::getCurrentUserID();
3120
3121         // params
3122         $gid = $_REQUEST['list_id'] ?? 0;
3123
3124         // error if no gid specified
3125         if ($gid == 0) {
3126                 throw new BadRequestException('gid not specified');
3127         }
3128
3129         // get data of the specified group id
3130         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
3131         // error message if specified gid is not in database
3132         if (!$group) {
3133                 throw new BadRequestException('gid not available');
3134         }
3135
3136         if (Group::remove($gid)) {
3137                 $list = [
3138                         'name' => $group['name'],
3139                         'id' => intval($gid),
3140                         'id_str' => (string) $gid,
3141                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
3142                 ];
3143
3144                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
3145         }
3146 }
3147
3148 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
3149
3150 /**
3151  * Create the specified group with the posted array of contacts.
3152  *
3153  * @param string $type Return type (atom, rss, xml, json)
3154  *
3155  * @return array|string
3156  * @throws BadRequestException
3157  * @throws ForbiddenException
3158  * @throws ImagickException
3159  * @throws InternalServerErrorException
3160  * @throws UnauthorizedException
3161  */
3162 function api_friendica_group_create($type)
3163 {
3164         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3165         $uid = BaseApi::getCurrentUserID();
3166
3167         // params
3168         $name = $_REQUEST['name'] ?? '';
3169         $json = json_decode($_POST['json'], true);
3170         $users = $json['user'];
3171
3172         $success = group_create($name, $uid, $users);
3173
3174         return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
3175 }
3176
3177 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3178
3179 /**
3180  * Create a new group.
3181  *
3182  * @param string $type Return type (atom, rss, xml, json)
3183  *
3184  * @return array|string
3185  * @throws BadRequestException
3186  * @throws ForbiddenException
3187  * @throws ImagickException
3188  * @throws InternalServerErrorException
3189  * @throws UnauthorizedException
3190  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
3191  */
3192 function api_lists_create($type)
3193 {
3194         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3195         $uid = BaseApi::getCurrentUserID();
3196
3197         // params
3198         $name = $_REQUEST['name'] ?? '';
3199
3200         $success = group_create($name, $uid);
3201         if ($success['success']) {
3202                 $grp = [
3203                         'name' => $success['name'],
3204                         'id' => intval($success['gid']),
3205                         'id_str' => (string) $success['gid'],
3206                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
3207                 ];
3208
3209                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
3210         }
3211 }
3212
3213 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
3214
3215 /**
3216  * Update the specified group with the posted array of contacts.
3217  *
3218  * @param string $type Return type (atom, rss, xml, json)
3219  *
3220  * @return array|string
3221  * @throws BadRequestException
3222  * @throws ForbiddenException
3223  * @throws ImagickException
3224  * @throws InternalServerErrorException
3225  * @throws UnauthorizedException
3226  */
3227 function api_friendica_group_update($type)
3228 {
3229         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3230         $uid = BaseApi::getCurrentUserID();
3231
3232         // params
3233         $gid = $_REQUEST['gid'] ?? 0;
3234         $name = $_REQUEST['name'] ?? '';
3235         $json = json_decode($_POST['json'], true);
3236         $users = $json['user'];
3237
3238         // error if no name specified
3239         if ($name == "") {
3240                 throw new BadRequestException('group name not specified');
3241         }
3242
3243         // error if no gid specified
3244         if ($gid == "") {
3245                 throw new BadRequestException('gid not specified');
3246         }
3247
3248         // remove members
3249         $members = Contact\Group::getById($gid);
3250         foreach ($members as $member) {
3251                 $cid = $member['id'];
3252                 foreach ($users as $user) {
3253                         $found = ($user['cid'] == $cid ? true : false);
3254                 }
3255                 if (!isset($found) || !$found) {
3256                         $gid = Group::getIdByName($uid, $name);
3257                         Group::removeMember($gid, $cid);
3258                 }
3259         }
3260
3261         // add members
3262         $erroraddinguser = false;
3263         $errorusers = [];
3264         foreach ($users as $user) {
3265                 $cid = $user['cid'];
3266
3267                 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
3268                         Group::addMember($gid, $cid);
3269                 } else {
3270                         $erroraddinguser = true;
3271                         $errorusers[] = $cid;
3272                 }
3273         }
3274
3275         // return success message incl. missing users in array
3276         $status = ($erroraddinguser ? "missing user" : "ok");
3277         $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
3278         return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
3279 }
3280
3281 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3282
3283 /**
3284  * Update information about a group.
3285  *
3286  * @param string $type Return type (atom, rss, xml, json)
3287  *
3288  * @return array|string
3289  * @throws BadRequestException
3290  * @throws ForbiddenException
3291  * @throws ImagickException
3292  * @throws InternalServerErrorException
3293  * @throws UnauthorizedException
3294  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
3295  */
3296 function api_lists_update($type)
3297 {
3298         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3299         $uid = BaseApi::getCurrentUserID();
3300
3301         // params
3302         $gid = $_REQUEST['list_id'] ?? 0;
3303         $name = $_REQUEST['name'] ?? '';
3304
3305         // error if no gid specified
3306         if ($gid == 0) {
3307                 throw new BadRequestException('gid not specified');
3308         }
3309
3310         // get data of the specified group id
3311         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
3312         // error message if specified gid is not in database
3313         if (!$group) {
3314                 throw new BadRequestException('gid not available');
3315         }
3316
3317         if (Group::update($gid, $name)) {
3318                 $list = [
3319                         'name' => $name,
3320                         'id' => intval($gid),
3321                         'id_str' => (string) $gid,
3322                         'user' => DI::twitterUser()->createFromUserId($uid, true)->toArray()
3323                 ];
3324
3325                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
3326         }
3327 }
3328
3329 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
3330
3331 /**
3332  * Set notification as seen and returns associated item (if possible)
3333  *
3334  * POST request with 'id' param as notification id
3335  *
3336  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3337  * @return string|array
3338  * @throws BadRequestException
3339  * @throws ForbiddenException
3340  * @throws ImagickException
3341  * @throws InternalServerErrorException
3342  * @throws UnauthorizedException
3343  */
3344 function api_friendica_notification_seen($type)
3345 {
3346         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3347         $uid = BaseApi::getCurrentUserID();
3348
3349         if (DI::args()->getArgc() !== 4) {
3350                 throw new BadRequestException('Invalid argument count');
3351         }
3352
3353         $id = intval($_REQUEST['id'] ?? 0);
3354
3355         try {
3356                 $Notify = DI::notify()->selectOneById($id);
3357                 if ($Notify->uid !== $uid) {
3358                         throw new NotFoundException();
3359                 }
3360
3361                 if ($Notify->uriId) {
3362                         DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
3363                 }
3364
3365                 $Notify->setSeen();
3366                 DI::notify()->save($Notify);
3367
3368                 if ($Notify->otype === Notification\ObjectType::ITEM) {
3369                         $item = Post::selectFirstForUser($uid, [], ['id' => $Notify->iid, 'uid' => $uid]);
3370                         if (DBA::isResult($item)) {
3371                                 $include_entities = strtolower(($_REQUEST['include_entities'] ?? 'false') == 'true');
3372
3373                                 // we found the item, return it to the user
3374                                 $ret = [DI::twitterStatus()->createFromUriId($item['uri-id'], $item['uid'], $include_entities)->toArray()];
3375                                 $data = ['status' => $ret];
3376                                 return DI::apiResponse()->formatData('status', $type, $data);
3377                         }
3378                         // the item can't be found, but we set the notification as seen, so we count this as a success
3379                 }
3380
3381                 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
3382         } catch (NotFoundException $e) {
3383                 throw new BadRequestException('Invalid argument', $e);
3384         } catch (Exception $e) {
3385                 throw new InternalServerErrorException('Internal Server exception', $e);
3386         }
3387 }
3388
3389 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3390
3391 /**
3392  * search for direct_messages containing a searchstring through api
3393  *
3394  * @param string $type      Known types are 'atom', 'rss', 'xml' and 'json'
3395  * @param string $box
3396  * @return string|array (success: success=true if found and search_result contains found messages,
3397  *                          success=false if nothing was found, search_result='nothing found',
3398  *                          error: result=error with error message)
3399  * @throws BadRequestException
3400  * @throws ForbiddenException
3401  * @throws ImagickException
3402  * @throws InternalServerErrorException
3403  * @throws UnauthorizedException
3404  */
3405 function api_friendica_direct_messages_search($type, $box = "")
3406 {
3407         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3408         $uid = BaseApi::getCurrentUserID();
3409
3410         // params
3411         $user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
3412         $searchstring = $_REQUEST['searchstring'] ?? '';
3413
3414         // error if no searchstring specified
3415         if ($searchstring == "") {
3416                 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
3417                 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
3418         }
3419
3420         // get data for the specified searchstring
3421         $r = DBA::toArray(DBA::p(
3422                 "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",
3423                 $uid,
3424                 '%'.$searchstring.'%'
3425         ));
3426
3427         $profile_url = $user_info["url"];
3428
3429         // message if nothing was found
3430         if (!DBA::isResult($r)) {
3431                 $success = ['success' => false, 'search_results' => 'problem with query'];
3432         } elseif (count($r) == 0) {
3433                 $success = ['success' => false, 'search_results' => 'nothing found'];
3434         } else {
3435                 $ret = [];
3436                 foreach ($r as $item) {
3437                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
3438                                 $recipient = $user_info;
3439                                 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
3440                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3441                                 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
3442                                 $sender = $user_info;
3443                         }
3444
3445                         if (isset($recipient) && isset($sender)) {
3446                                 $ret[] = api_format_messages($item, $recipient, $sender);
3447                         }
3448                 }
3449                 $success = ['success' => true, 'search_results' => $ret];
3450         }
3451
3452         return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
3453 }
3454
3455 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);