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