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