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