]> git.mxchange.org Git - friendica.git/blob - include/api.php
API: moved classes / unified user array creation
[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\ContactSelector;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Core\System;
33 use Friendica\Database\DBA;
34 use Friendica\DI;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Group;
37 use Friendica\Model\Item;
38 use Friendica\Model\Mail;
39 use Friendica\Model\Notification;
40 use Friendica\Model\Photo;
41 use Friendica\Model\Post;
42 use Friendica\Model\Profile;
43 use Friendica\Model\User;
44 use Friendica\Model\Verb;
45 use Friendica\Module\Api\ApiResponse;
46 use Friendica\Module\BaseApi;
47 use Friendica\Network\HTTPException;
48 use Friendica\Network\HTTPException\BadRequestException;
49 use Friendica\Network\HTTPException\ForbiddenException;
50 use Friendica\Network\HTTPException\InternalServerErrorException;
51 use Friendica\Network\HTTPException\MethodNotAllowedException;
52 use Friendica\Network\HTTPException\NotFoundException;
53 use Friendica\Network\HTTPException\TooManyRequestsException;
54 use Friendica\Network\HTTPException\UnauthorizedException;
55 use Friendica\Object\Image;
56 use Friendica\Protocol\Activity;
57 use Friendica\Security\BasicAuth;
58 use Friendica\Security\OAuth;
59 use Friendica\Util\DateTimeFormat;
60 use Friendica\Util\Images;
61 use Friendica\Util\Network;
62 use Friendica\Util\Proxy;
63 use Friendica\Util\Strings;
64
65 require_once __DIR__ . '/../mod/item.php';
66 require_once __DIR__ . '/../mod/wall_upload.php';
67
68 define('API_METHOD_ANY', '*');
69 define('API_METHOD_GET', 'GET');
70 define('API_METHOD_POST', 'POST,PUT');
71 define('API_METHOD_DELETE', 'POST,DELETE');
72
73 define('API_LOG_PREFIX', 'API {action} - ');
74
75 $API = [];
76 $called_api = [];
77
78 /**
79  * Auth API user
80  *
81  * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
82  * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
83  * into a page, and visitors will post something without noticing it).
84  */
85 function api_user()
86 {
87         $user = OAuth::getCurrentUserID();
88         if (!empty($user)) {
89                 return $user;
90         }
91
92         if (!empty($_SESSION['allow_api'])) {
93                 return local_user();
94         }
95
96         return false;
97 }
98
99 /**
100  * Get source name from API client
101  *
102  * Clients can send 'source' parameter to be show in post metadata
103  * as "sent via <source>".
104  * Some clients doesn't send a source param, we support ones we know
105  * (only Twidere, atm)
106  *
107  * @return string
108  *        Client source name, default to "api" if unset/unknown
109  * @throws Exception
110  */
111 function api_source()
112 {
113         if (requestdata('source')) {
114                 return requestdata('source');
115         }
116
117         // Support for known clients that doesn't send a source name
118         if (!empty($_SERVER['HTTP_USER_AGENT'])) {
119                 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
120                         return "Twidere";
121                 }
122
123                 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
124         } else {
125                 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
126         }
127
128         return "api";
129 }
130
131 /**
132  * Format date for API
133  *
134  * @param string $str Source date, as UTC
135  * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
136  * @throws Exception
137  */
138 function api_date($str)
139 {
140         // Wed May 23 06:01:13 +0000 2007
141         return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
142 }
143
144 /**
145  * Register a function to be the endpoint for defined API path.
146  *
147  * @param string $path   API URL path, relative to DI::baseUrl()
148  * @param string $func   Function name to call on path request
149  * @param bool   $auth   API need logged user
150  * @param string $method HTTP method reqiured to call this endpoint.
151  *                       One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
152  *                       Default to API_METHOD_ANY
153  */
154 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
155 {
156         global $API;
157
158         $API[$path] = [
159                 'func'   => $func,
160                 'auth'   => $auth,
161                 'method' => $method,
162         ];
163
164         // Workaround for hotot
165         $path = str_replace("api/", "api/1.1/", $path);
166
167         $API[$path] = [
168                 'func'   => $func,
169                 'auth'   => $auth,
170                 'method' => $method,
171         ];
172 }
173
174 /**
175  * Check HTTP method of called API
176  *
177  * API endpoints can define which HTTP method to accept when called.
178  * This function check the current HTTP method agains endpoint
179  * registered method.
180  *
181  * @param string $method Required methods, uppercase, separated by comma
182  * @return bool
183  */
184 function api_check_method($method)
185 {
186         if ($method == "*") {
187                 return true;
188         }
189         return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
190 }
191
192 /**
193  * Main API entry point
194  *
195  * Authenticate user, call registered API function, set HTTP headers
196  *
197  * @param App $a App
198  * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
199  * @return string|array API call result
200  * @throws Exception
201  */
202 function api_call(App $a, App\Arguments $args = null)
203 {
204         global $API, $called_api;
205
206         if ($args == null) {
207                 $args = DI::args();
208         }
209
210         $type = "json";
211         if (strpos($args->getCommand(), ".xml") > 0) {
212                 $type = "xml";
213         }
214         if (strpos($args->getCommand(), ".json") > 0) {
215                 $type = "json";
216         }
217         if (strpos($args->getCommand(), ".rss") > 0) {
218                 $type = "rss";
219         }
220         if (strpos($args->getCommand(), ".atom") > 0) {
221                 $type = "atom";
222         }
223
224         try {
225                 foreach ($API as $p => $info) {
226                         if (strpos($args->getCommand(), $p) === 0) {
227                                 if (!api_check_method($info['method'])) {
228                                         throw new MethodNotAllowedException();
229                                 }
230
231                                 $called_api = explode("/", $p);
232
233                                 if (!empty($info['auth']) && api_user() === false) {
234                                         BasicAuth::getCurrentUserID(true);
235                                         Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
236                                 }
237
238                                 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
239
240                                 $stamp =  microtime(true);
241                                 $return = call_user_func($info['func'], $type);
242                                 $duration = floatval(microtime(true) - $stamp);
243
244                                 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
245
246                                 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
247
248                                 if (false === $return) {
249                                         /*
250                                                 * api function returned false withour throw an
251                                                 * exception. This should not happend, throw a 500
252                                                 */
253                                         throw new InternalServerErrorException();
254                                 }
255
256                                 switch ($type) {
257                                         case "xml":
258                                                 header("Content-Type: text/xml");
259                                                 break;
260                                         case "json":
261                                                 header("Content-Type: application/json");
262                                                 if (!empty($return)) {
263                                                         $json = json_encode(end($return));
264                                                         if (!empty($_GET['callback'])) {
265                                                                 $json = $_GET['callback'] . "(" . $json . ")";
266                                                         }
267                                                         $return = $json;
268                                                 }
269                                                 break;
270                                         case "rss":
271                                                 header("Content-Type: application/rss+xml");
272                                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
273                                                 break;
274                                         case "atom":
275                                                 header("Content-Type: application/atom+xml");
276                                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
277                                                 break;
278                                 }
279                                 return $return;
280                         }
281                 }
282
283                 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
284                 throw new NotFoundException();
285         } catch (HTTPException $e) {
286                 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
287         }
288 }
289
290 /**
291  * Set values for RSS template
292  *
293  * @param App   $a
294  * @param array $arr       Array to be passed to template
295  * @param array $user_info User info
296  * @return array
297  * @throws BadRequestException
298  * @throws ImagickException
299  * @throws InternalServerErrorException
300  * @throws UnauthorizedException
301  * @todo  find proper type-hints
302  */
303 function api_rss_extra(App $a, $arr, $user_info)
304 {
305         if (is_null($user_info)) {
306                 $user_info = api_get_user();
307         }
308
309         $arr['$user'] = $user_info;
310         $arr['$rss'] = [
311                 'alternate'    => $user_info['url'],
312                 'self'         => DI::baseUrl() . "/" . DI::args()->getQueryString(),
313                 'base'         => DI::baseUrl(),
314                 'updated'      => api_date(null),
315                 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
316                 'language'     => $user_info['lang'],
317                 'logo'         => DI::baseUrl() . "/images/friendica-32.png",
318         ];
319
320         return $arr;
321 }
322
323
324 /**
325  * Unique contact to contact url.
326  *
327  * @param int $id Contact id
328  * @return bool|string
329  *                Contact url or False if contact id is unknown
330  * @throws Exception
331  */
332 function api_unique_id_to_nurl($id)
333 {
334         $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
335
336         if (DBA::isResult($r)) {
337                 return $r["nurl"];
338         } else {
339                 return false;
340         }
341 }
342
343 /**
344  * Get user info array.
345  *
346  * @param App        $a          App
347  * @param int|string $contact_id Contact ID or URL
348  * @return array|bool
349  * @throws BadRequestException
350  * @throws ImagickException
351  * @throws InternalServerErrorException
352  * @throws UnauthorizedException
353  */
354 function api_get_user($contact_id = null)
355 {
356         global $called_api;
357
358         $user = null;
359         $extra_query = "";
360         $url = "";
361
362         Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
363
364         // Searching for contact URL
365         if (!is_null($contact_id) && (intval($contact_id) == 0)) {
366                 $user = Strings::normaliseLink($contact_id);
367                 $url = $user;
368                 $extra_query = "AND `contact`.`nurl` = ? ";
369                 if (api_user() !== false) {
370                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
371                 }
372         }
373
374         // Searching for contact id with uid = 0
375         if (!is_null($contact_id) && (intval($contact_id) != 0)) {
376                 $user = api_unique_id_to_nurl(intval($contact_id));
377
378                 if ($user == "") {
379                         throw new BadRequestException("User ID ".$contact_id." not found.");
380                 }
381
382                 $url = $user;
383                 $extra_query = "AND `contact`.`nurl` = ? ";
384                 if (api_user() !== false) {
385                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
386                 }
387         }
388
389         if (is_null($user) && !empty($_GET['user_id'])) {
390                 $user = api_unique_id_to_nurl($_GET['user_id']);
391
392                 if ($user == "") {
393                         throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
394                 }
395
396                 $url = $user;
397                 $extra_query = "AND `contact`.`nurl` = ? ";
398                 if (api_user() !== false) {
399                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
400                 }
401         }
402         if (is_null($user) && !empty($_GET['screen_name'])) {
403                 $user = $_GET['screen_name'];
404                 $extra_query = "AND `contact`.`nick` = ? ";
405                 if (api_user() !== false) {
406                         $extra_query .= "AND `contact`.`uid`=".intval(api_user());
407                 }
408         }
409
410         if (is_null($user) && !empty($_GET['profileurl'])) {
411                 $user = Strings::normaliseLink($_GET['profileurl']);
412                 $extra_query = "AND `contact`.`nurl` = ? ";
413                 if (api_user() !== false) {
414                         $extra_query .= "AND `contact`.`uid`=".intval(api_user());
415                 }
416         }
417
418         // $called_api is the API path exploded on / and is expected to have at least 2 elements
419         if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) {
420                 $argid = count($called_api);
421                 if (!empty(DI::args()->getArgv()[$argid])) {
422                         $data = explode(".", DI::args()->getArgv()[$argid]);
423                         if (count($data) > 1) {
424                                 [$user, $null] = $data;
425                         }
426                 }
427                 if (is_numeric($user)) {
428                         $user = api_unique_id_to_nurl(intval($user));
429
430                         if ($user != "") {
431                                 $url = $user;
432                                 $extra_query = "AND `contact`.`nurl` = ? ";
433                                 if (api_user() !== false) {
434                                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
435                                 }
436                         }
437                 } else {
438                         $extra_query = "AND `contact`.`nick` = ? ";
439                         if (api_user() !== false) {
440                                 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
441                         }
442                 }
443         }
444
445         Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
446
447         if (!$user) {
448                 if (api_user() === false) {
449                         BasicAuth::getCurrentUserID(true);
450                         return false;
451                 } else {
452                         $user = api_user();
453                         $extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
454                 }
455         }
456
457         Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
458
459         // user info
460         $uinfo = DBA::toArray(DBA::p(
461                 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
462                         WHERE 1
463                 $extra_query",
464                 $user
465         ));
466
467         if (DBA::isResult($uinfo)) {
468                 // Selecting the id by priority, friendica first
469                 api_best_nickname($uinfo);
470                 return DI::twitterUser()->createFromContactId($uinfo[0]['cid'], $uinfo[0]['uid'])->toArray();
471         }
472
473         if ($url == "") {
474                 throw new BadRequestException("User not found.");
475         }
476
477         $cid = Contact::getIdForURL($url, 0, false);
478
479         if (!empty($cid)) {
480                 return DI::twitterUser()->createFromContactId($cid, 0)->toArray();
481         } else {
482                 throw new BadRequestException("User ".$url." not found.");
483         }
484 }
485
486 /**
487  * return api-formatted array for item's author and owner
488  *
489  * @param App   $a    App
490  * @param array $item item from db
491  * @return array(array:author, array:owner)
492  * @throws BadRequestException
493  * @throws ImagickException
494  * @throws InternalServerErrorException
495  * @throws UnauthorizedException
496  */
497 function api_item_get_user(App $a, $item)
498 {
499         $status_user = api_get_user($item['author-id'] ?? null);
500
501         $author_user = $status_user;
502
503         $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
504
505         if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
506                 $owner_user = api_get_user($item['owner-id'] ?? null);
507         } else {
508                 $owner_user = $author_user;
509         }
510
511         return ([$status_user, $author_user, $owner_user]);
512 }
513
514 /**
515  * TWITTER API
516  */
517
518 /**
519  * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
520  * returns a 401 status code and an error message if not.
521  *
522  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
523  *
524  * @param string $type Return type (atom, rss, xml, json)
525  * @return array|string
526  * @throws BadRequestException
527  * @throws ForbiddenException
528  * @throws ImagickException
529  * @throws InternalServerErrorException
530  * @throws UnauthorizedException
531  */
532 function api_account_verify_credentials($type)
533 {
534         $a = DI::app();
535
536         if (api_user() === false) {
537                 throw new ForbiddenException();
538         }
539
540         unset($_REQUEST["user_id"]);
541         unset($_GET["user_id"]);
542
543         unset($_REQUEST["screen_name"]);
544         unset($_GET["screen_name"]);
545
546         $skip_status = $_REQUEST['skip_status'] ?? false;
547
548         $user_info = api_get_user();
549
550         // "verified" isn't used here in the standard
551         unset($user_info["verified"]);
552
553         // - Adding last status
554         if (!$skip_status) {
555                 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
556                 if (!empty($item)) {
557                         $user_info['status'] = api_format_item($item, $type);
558                 }
559         }
560
561         // "uid" and "self" are only needed for some internal stuff, so remove it from here
562         unset($user_info["uid"]);
563         unset($user_info["self"]);
564
565         return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
566 }
567
568 /// @TODO move to top of file or somewhere better
569 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
570
571 /**
572  * Get data from $_POST or $_GET
573  *
574  * @param string $k
575  * @return null
576  */
577 function requestdata($k)
578 {
579         if (!empty($_POST[$k])) {
580                 return $_POST[$k];
581         }
582         if (!empty($_GET[$k])) {
583                 return $_GET[$k];
584         }
585         return null;
586 }
587
588 /**
589  * Deprecated function to upload media.
590  *
591  * @param string $type Return type (atom, rss, xml, json)
592  *
593  * @return array|string
594  * @throws BadRequestException
595  * @throws ForbiddenException
596  * @throws ImagickException
597  * @throws InternalServerErrorException
598  * @throws UnauthorizedException
599  */
600 function api_statuses_mediap($type)
601 {
602         $a = DI::app();
603
604         if (api_user() === false) {
605                 logger::notice('api_statuses_update: no user');
606                 throw new ForbiddenException();
607         }
608         $user_info = api_get_user();
609
610         $_REQUEST['profile_uid'] = api_user();
611         $_REQUEST['api_source'] = true;
612         $txt = requestdata('status') ?? '';
613         /// @TODO old-lost code?
614         //$txt = urldecode(requestdata('status'));
615
616         if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
617                 $txt = HTML::toBBCodeVideo($txt);
618                 $config = HTMLPurifier_Config::createDefault();
619                 $config->set('Cache.DefinitionImpl', null);
620                 $purifier = new HTMLPurifier($config);
621                 $txt = $purifier->purify($txt);
622         }
623         $txt = HTML::toBBCode($txt);
624
625         DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
626
627         $picture = wall_upload_post($a, false);
628
629         // now that we have the img url in bbcode we can add it to the status and insert the wall item.
630         $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
631         $item_id = item_post($a);
632
633         // output the post that we just posted.
634         return api_status_show($type, $item_id);
635 }
636
637 /// @TODO move this to top of file or somewhere better!
638 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
639
640 /**
641  * Updates the user’s current status.
642  *
643  * @param string $type Return type (atom, rss, xml, json)
644  *
645  * @return array|string
646  * @throws BadRequestException
647  * @throws ForbiddenException
648  * @throws ImagickException
649  * @throws InternalServerErrorException
650  * @throws TooManyRequestsException
651  * @throws UnauthorizedException
652  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
653  */
654 function api_statuses_update($type)
655 {
656         $a = DI::app();
657
658         if (api_user() === false) {
659                 logger::notice('api_statuses_update: no user');
660                 throw new ForbiddenException();
661         }
662
663         api_get_user();
664
665         // convert $_POST array items to the form we use for web posts.
666         if (requestdata('htmlstatus')) {
667                 $txt = requestdata('htmlstatus') ?? '';
668                 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
669                         $txt = HTML::toBBCodeVideo($txt);
670
671                         $config = HTMLPurifier_Config::createDefault();
672                         $config->set('Cache.DefinitionImpl', null);
673
674                         $purifier = new HTMLPurifier($config);
675                         $txt = $purifier->purify($txt);
676
677                         $_REQUEST['body'] = HTML::toBBCode($txt);
678                 }
679         } else {
680                 $_REQUEST['body'] = requestdata('status');
681         }
682
683         $_REQUEST['title'] = requestdata('title');
684
685         $parent = requestdata('in_reply_to_status_id');
686
687         // Twidere sends "-1" if it is no reply ...
688         if ($parent == -1) {
689                 $parent = "";
690         }
691
692         if (ctype_digit($parent)) {
693                 $_REQUEST['parent'] = $parent;
694         } else {
695                 $_REQUEST['parent_uri'] = $parent;
696         }
697
698         if (requestdata('lat') && requestdata('long')) {
699                 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
700         }
701         $_REQUEST['profile_uid'] = api_user();
702
703         if (!$parent) {
704                 // Check for throttling (maximum posts per day, week and month)
705                 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
706                 if ($throttle_day > 0) {
707                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
708
709                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
710                         $posts_day = Post::count($condition);
711
712                         if ($posts_day > $throttle_day) {
713                                 logger::info('Daily posting limit reached for user '.api_user());
714                                 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
715                                 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));
716                         }
717                 }
718
719                 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
720                 if ($throttle_week > 0) {
721                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
722
723                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
724                         $posts_week = Post::count($condition);
725
726                         if ($posts_week > $throttle_week) {
727                                 logger::info('Weekly posting limit reached for user '.api_user());
728                                 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
729                                 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));
730                         }
731                 }
732
733                 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
734                 if ($throttle_month > 0) {
735                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
736
737                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
738                         $posts_month = Post::count($condition);
739
740                         if ($posts_month > $throttle_month) {
741                                 logger::info('Monthly posting limit reached for user '.api_user());
742                                 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
743                                 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));
744                         }
745                 }
746         }
747
748         if (requestdata('media_ids')) {
749                 $ids = explode(',', requestdata('media_ids') ?? '');
750         } elseif (!empty($_FILES['media'])) {
751                 // upload the image if we have one
752                 $picture = wall_upload_post($a, false);
753                 if (is_array($picture)) {
754                         $ids[] = $picture['id'];
755                 }
756         }
757
758         $attachments = [];
759         $ressources = [];
760
761         if (!empty($ids)) {
762                 foreach ($ids as $id) {
763                         $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
764                                         INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
765                                                 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
766                                         ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
767
768                         if (!empty($media)) {
769                                 $ressources[] = $media[0]['resource-id'];
770                                 $phototypes = Images::supportedTypes();
771                                 $ext = $phototypes[$media[0]['type']];
772
773                                 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
774                                         'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
775                                         'size' => $media[0]['datasize'],
776                                         'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
777                                         'description' => $media[0]['desc'] ?? '',
778                                         'width' => $media[0]['width'],
779                                         'height' => $media[0]['height']];
780
781                                 if (count($media) > 1) {
782                                         $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
783                                         $attachment['preview-width'] = $media[1]['width'];
784                                         $attachment['preview-height'] = $media[1]['height'];
785                                 }
786                                 $attachments[] = $attachment;
787                         }
788                 }
789
790                 // We have to avoid that the post is rejected because of an empty body
791                 if (empty($_REQUEST['body'])) {
792                         $_REQUEST['body'] = '[hr]';
793                 }
794         }
795
796         if (!empty($attachments)) {
797                 $_REQUEST['attachments'] = $attachments;
798         }
799
800         // set this so that the item_post() function is quiet and doesn't redirect or emit json
801
802         $_REQUEST['api_source'] = true;
803
804         if (empty($_REQUEST['source'])) {
805                 $_REQUEST["source"] = api_source();
806         }
807
808         // call out normal post function
809         $item_id = item_post($a);
810
811         if (!empty($ressources) && !empty($item_id)) {
812                 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
813                 foreach ($ressources as $ressource) {
814                         Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
815                 }
816         }
817
818         // output the post that we just posted.
819         return api_status_show($type, $item_id);
820 }
821
822 /// @TODO move to top of file or somewhere better
823 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
824 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
825
826 /**
827  * Uploads an image to Friendica.
828  *
829  * @return array
830  * @throws BadRequestException
831  * @throws ForbiddenException
832  * @throws ImagickException
833  * @throws InternalServerErrorException
834  * @throws UnauthorizedException
835  * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
836  */
837 function api_media_upload()
838 {
839         $a = DI::app();
840
841         if (api_user() === false) {
842                 logger::notice('no user');
843                 throw new ForbiddenException();
844         }
845
846         api_get_user();
847
848         if (empty($_FILES['media'])) {
849                 // Output error
850                 throw new BadRequestException("No media.");
851         }
852
853         $media = wall_upload_post($a, false);
854         if (!$media) {
855                 // Output error
856                 throw new InternalServerErrorException();
857         }
858
859         $returndata = [];
860         $returndata["media_id"] = $media["id"];
861         $returndata["media_id_string"] = (string)$media["id"];
862         $returndata["size"] = $media["size"];
863         $returndata["image"] = ["w" => $media["width"],
864                                 "h" => $media["height"],
865                                 "image_type" => $media["type"],
866                                 "friendica_preview_url" => $media["preview"]];
867
868         Logger::info('Media uploaded', ['return' => $returndata]);
869
870         return ["media" => $returndata];
871 }
872
873 /// @TODO move to top of file or somewhere better
874 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
875
876 /**
877  * Updates media meta data (picture descriptions)
878  *
879  * @param string $type Return type (atom, rss, xml, json)
880  *
881  * @return array|string
882  * @throws BadRequestException
883  * @throws ForbiddenException
884  * @throws ImagickException
885  * @throws InternalServerErrorException
886  * @throws TooManyRequestsException
887  * @throws UnauthorizedException
888  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
889  *
890  * @todo Compare the corresponding Twitter function for correct return values
891  */
892 function api_media_metadata_create($type)
893 {
894         $a = DI::app();
895
896         if (api_user() === false) {
897                 Logger::info('no user');
898                 throw new ForbiddenException();
899         }
900
901         api_get_user();
902
903         $postdata = Network::postdata();
904
905         if (empty($postdata)) {
906                 throw new BadRequestException("No post data");
907         }
908
909         $data = json_decode($postdata, true);
910         if (empty($data)) {
911                 throw new BadRequestException("Invalid post data");
912         }
913
914         if (empty($data['media_id']) || empty($data['alt_text'])) {
915                 throw new BadRequestException("Missing post data values");
916         }
917
918         if (empty($data['alt_text']['text'])) {
919                 throw new BadRequestException("No alt text.");
920         }
921
922         Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
923
924         $condition =  ['id' => $data['media_id'], 'uid' => api_user()];
925         $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
926         if (!DBA::isResult($photo)) {
927                 throw new BadRequestException("Metadata not found.");
928         }
929
930         DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
931 }
932
933 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
934
935 /**
936  * @param string $type    Return format (atom, rss, xml, json)
937  * @param int    $item_id
938  * @return array|string
939  * @throws Exception
940  */
941 function api_status_show($type, $item_id)
942 {
943         Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
944
945         $status_info = [];
946
947         $item = api_get_item(['id' => $item_id]);
948         if (!empty($item)) {
949                 $status_info = api_format_item($item, $type);
950         }
951
952         Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
953
954         return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
955 }
956
957 /**
958  * Retrieves the last public status of the provided user info
959  *
960  * @param int    $ownerId Public contact Id
961  * @param int    $uid     User Id
962  * @return array
963  * @throws Exception
964  */
965 function api_get_last_status($ownerId, $uid)
966 {
967         $condition = [
968                 'author-id'=> $ownerId,
969                 'uid'      => $uid,
970                 'gravity'  => [GRAVITY_PARENT, GRAVITY_COMMENT],
971                 'private'  => [Item::PUBLIC, Item::UNLISTED]
972         ];
973
974         $item = api_get_item($condition);
975
976         return $item;
977 }
978
979 /**
980  * Retrieves a single item record based on the provided condition and converts it for API use.
981  *
982  * @param array $condition Item table condition array
983  * @return array
984  * @throws Exception
985  */
986 function api_get_item(array $condition)
987 {
988         $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
989
990         return $item;
991 }
992
993 /**
994  * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
995  * The author's most recent status will be returned inline.
996  *
997  * @param string $type Return type (atom, rss, xml, json)
998  * @return array|string
999  * @throws BadRequestException
1000  * @throws ImagickException
1001  * @throws InternalServerErrorException
1002  * @throws UnauthorizedException
1003  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1004  */
1005 function api_users_show($type)
1006 {
1007         $a = Friendica\DI::app();
1008
1009         $user_info = api_get_user();
1010
1011         $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1012         if (!empty($item)) {
1013                 $user_info['status'] = api_format_item($item, $type);
1014         }
1015
1016         // "uid" and "self" are only needed for some internal stuff, so remove it from here
1017         unset($user_info['uid']);
1018         unset($user_info['self']);
1019
1020         return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
1021 }
1022
1023 /// @TODO move to top of file or somewhere better
1024 api_register_func('api/users/show', 'api_users_show');
1025 api_register_func('api/externalprofile/show', 'api_users_show');
1026
1027 /**
1028  * Search a public user account.
1029  *
1030  * @param string $type Return type (atom, rss, xml, json)
1031  *
1032  * @return array|string
1033  * @throws BadRequestException
1034  * @throws ImagickException
1035  * @throws InternalServerErrorException
1036  * @throws UnauthorizedException
1037  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1038  */
1039 function api_users_search($type)
1040 {
1041         $a = DI::app();
1042
1043         $userlist = [];
1044
1045         if (!empty($_GET['q'])) {
1046                 $contacts = Contact::selectToArray(
1047                         ['id'],
1048                         [
1049                                 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1050                                 $_GET['q'],
1051                                 $_GET['q'],
1052                                 $_GET['q'],
1053                                 $_GET['q'],
1054                         ]
1055                 );
1056
1057                 if (DBA::isResult($contacts)) {
1058                         $k = 0;
1059                         foreach ($contacts as $contact) {
1060                                 $user_info = api_get_user($contact['id']);
1061
1062                                 if ($type == 'xml') {
1063                                         $userlist[$k++ . ':user'] = $user_info;
1064                                 } else {
1065                                         $userlist[] = $user_info;
1066                                 }
1067                         }
1068                         $userlist = ['users' => $userlist];
1069                 } else {
1070                         throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1071                 }
1072         } else {
1073                 throw new BadRequestException('No search term specified.');
1074         }
1075
1076         return DI::apiResponse()->formatData('users', $type, $userlist);
1077 }
1078
1079 /// @TODO move to top of file or somewhere better
1080 api_register_func('api/users/search', 'api_users_search');
1081
1082 /**
1083  * Return user objects
1084  *
1085  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1086  *
1087  * @param string $type Return format: json or xml
1088  *
1089  * @return array|string
1090  * @throws BadRequestException
1091  * @throws ImagickException
1092  * @throws InternalServerErrorException
1093  * @throws NotFoundException if the results are empty.
1094  * @throws UnauthorizedException
1095  */
1096 function api_users_lookup($type)
1097 {
1098         $users = [];
1099
1100         if (!empty($_REQUEST['user_id'])) {
1101                 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1102                         if (!empty($id)) {
1103                                 $users[] = api_get_user($id);
1104                         }
1105                 }
1106         }
1107
1108         if (empty($users)) {
1109                 throw new NotFoundException;
1110         }
1111
1112         return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
1113 }
1114
1115 /// @TODO move to top of file or somewhere better
1116 api_register_func('api/users/lookup', 'api_users_lookup', true);
1117
1118 /**
1119  * Returns statuses that match a specified query.
1120  *
1121  * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1122  *
1123  * @param string $type Return format: json, xml, atom, rss
1124  *
1125  * @return array|string
1126  * @throws BadRequestException if the "q" parameter is missing.
1127  * @throws ForbiddenException
1128  * @throws ImagickException
1129  * @throws InternalServerErrorException
1130  * @throws UnauthorizedException
1131  */
1132 function api_search($type)
1133 {
1134         $a = DI::app();
1135         $user_info = api_get_user();
1136
1137         if (api_user() === false || $user_info === false) {
1138                 throw new ForbiddenException();
1139         }
1140
1141         if (empty($_REQUEST['q'])) {
1142                 throw new BadRequestException('q parameter is required.');
1143         }
1144
1145         $searchTerm = trim(rawurldecode($_REQUEST['q']));
1146
1147         $data = [];
1148         $data['status'] = [];
1149         $count = 15;
1150         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1151         if (!empty($_REQUEST['rpp'])) {
1152                 $count = $_REQUEST['rpp'];
1153         } elseif (!empty($_REQUEST['count'])) {
1154                 $count = $_REQUEST['count'];
1155         }
1156
1157         $since_id = $_REQUEST['since_id'] ?? 0;
1158         $max_id = $_REQUEST['max_id'] ?? 0;
1159         $page = $_REQUEST['page'] ?? 1;
1160
1161         $start = max(0, ($page - 1) * $count);
1162
1163         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1164         if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1165                 $searchTerm = $matches[1];
1166                 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1167                 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1168                 $uriids = [];
1169                 while ($tag = DBA::fetch($tags)) {
1170                         $uriids[] = $tag['uri-id'];
1171                 }
1172                 DBA::close($tags);
1173
1174                 if (empty($uriids)) {
1175                         return DI::apiResponse()->formatData('statuses', $type, $data);
1176                 }
1177
1178                 $condition = ['uri-id' => $uriids];
1179                 if ($exclude_replies) {
1180                         $condition['gravity'] = GRAVITY_PARENT;
1181                 }
1182
1183                 $params['group_by'] = ['uri-id'];
1184         } else {
1185                 $condition = ["`id` > ?
1186                         " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1187                         AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1188                         AND `body` LIKE CONCAT('%',?,'%')",
1189                         $since_id, api_user(), $_REQUEST['q']];
1190                 if ($max_id > 0) {
1191                         $condition[0] .= ' AND `id` <= ?';
1192                         $condition[] = $max_id;
1193                 }
1194         }
1195
1196         $statuses = [];
1197
1198         if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1199                 $id = Item::fetchByLink($searchTerm, api_user());
1200                 if (!$id) {
1201                         // Public post
1202                         $id = Item::fetchByLink($searchTerm);
1203                 }
1204
1205                 if (!empty($id)) {
1206                         $statuses = Post::select([], ['id' => $id]);
1207                 }
1208         }
1209
1210         $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1211
1212         $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1213
1214         bindComments($data['status']);
1215
1216         return DI::apiResponse()->formatData('statuses', $type, $data);
1217 }
1218
1219 /// @TODO move to top of file or somewhere better
1220 api_register_func('api/search/tweets', 'api_search', true);
1221 api_register_func('api/search', 'api_search', true);
1222
1223 /**
1224  * Returns the most recent statuses posted by the user and the users they follow.
1225  *
1226  * @see  https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1227  *
1228  * @param string $type Return type (atom, rss, xml, json)
1229  *
1230  * @return array|string
1231  * @throws BadRequestException
1232  * @throws ForbiddenException
1233  * @throws ImagickException
1234  * @throws InternalServerErrorException
1235  * @throws UnauthorizedException
1236  * @todo Optional parameters
1237  * @todo Add reply info
1238  */
1239 function api_statuses_home_timeline($type)
1240 {
1241         $a = DI::app();
1242         $user_info = api_get_user();
1243
1244         if (api_user() === false || $user_info === false) {
1245                 throw new ForbiddenException();
1246         }
1247
1248         unset($_REQUEST["user_id"]);
1249         unset($_GET["user_id"]);
1250
1251         unset($_REQUEST["screen_name"]);
1252         unset($_GET["screen_name"]);
1253
1254         // get last network messages
1255
1256         // params
1257         $count = $_REQUEST['count'] ?? 20;
1258         $page = $_REQUEST['page']?? 0;
1259         $since_id = $_REQUEST['since_id'] ?? 0;
1260         $max_id = $_REQUEST['max_id'] ?? 0;
1261         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1262         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1263
1264         $start = max(0, ($page - 1) * $count);
1265
1266         $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1267                 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1268
1269         if ($max_id > 0) {
1270                 $condition[0] .= " AND `id` <= ?";
1271                 $condition[] = $max_id;
1272         }
1273         if ($exclude_replies) {
1274                 $condition[0] .= ' AND `gravity` = ?';
1275                 $condition[] = GRAVITY_PARENT;
1276         }
1277         if ($conversation_id > 0) {
1278                 $condition[0] .= " AND `parent` = ?";
1279                 $condition[] = $conversation_id;
1280         }
1281
1282         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1283         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1284
1285         $items = Post::toArray($statuses);
1286
1287         $ret = api_format_items($items, $user_info, false, $type);
1288
1289         // Set all posts from the query above to seen
1290         $idarray = [];
1291         foreach ($items as $item) {
1292                 $idarray[] = intval($item["id"]);
1293         }
1294
1295         if (!empty($idarray)) {
1296                 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1297                 if ($unseen) {
1298                         Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1299                 }
1300         }
1301
1302         bindComments($ret);
1303
1304         $data = ['status' => $ret];
1305         switch ($type) {
1306                 case "atom":
1307                         break;
1308                 case "rss":
1309                         $data = api_rss_extra($a, $data, $user_info);
1310                         break;
1311         }
1312
1313         return DI::apiResponse()->formatData("statuses", $type, $data);
1314 }
1315
1316
1317 /// @TODO move to top of file or somewhere better
1318 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1319 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1320
1321 /**
1322  * Returns the most recent statuses from public users.
1323  *
1324  * @param string $type Return type (atom, rss, xml, json)
1325  *
1326  * @return array|string
1327  * @throws BadRequestException
1328  * @throws ForbiddenException
1329  * @throws ImagickException
1330  * @throws InternalServerErrorException
1331  * @throws UnauthorizedException
1332  */
1333 function api_statuses_public_timeline($type)
1334 {
1335         $a = DI::app();
1336         $user_info = api_get_user();
1337
1338         if (api_user() === false || $user_info === false) {
1339                 throw new ForbiddenException();
1340         }
1341
1342         // get last network messages
1343
1344         // params
1345         $count = $_REQUEST['count'] ?? 20;
1346         $page = $_REQUEST['page'] ?? 1;
1347         $since_id = $_REQUEST['since_id'] ?? 0;
1348         $max_id = $_REQUEST['max_id'] ?? 0;
1349         $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1350         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1351
1352         $start = max(0, ($page - 1) * $count);
1353
1354         if ($exclude_replies && !$conversation_id) {
1355                 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1356                         GRAVITY_PARENT, $since_id, Item::PUBLIC];
1357
1358                 if ($max_id > 0) {
1359                         $condition[0] .= " AND `id` <= ?";
1360                         $condition[] = $max_id;
1361                 }
1362
1363                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1364                 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1365
1366                 $r = Post::toArray($statuses);
1367         } else {
1368                 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1369                         GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1370
1371                 if ($max_id > 0) {
1372                         $condition[0] .= " AND `id` <= ?";
1373                         $condition[] = $max_id;
1374                 }
1375                 if ($conversation_id > 0) {
1376                         $condition[0] .= " AND `parent` = ?";
1377                         $condition[] = $conversation_id;
1378                 }
1379
1380                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1381                 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1382
1383                 $r = Post::toArray($statuses);
1384         }
1385
1386         $ret = api_format_items($r, $user_info, false, $type);
1387
1388         bindComments($ret);
1389
1390         $data = ['status' => $ret];
1391         switch ($type) {
1392                 case "atom":
1393                         break;
1394                 case "rss":
1395                         $data = api_rss_extra($a, $data, $user_info);
1396                         break;
1397         }
1398
1399         return DI::apiResponse()->formatData("statuses", $type, $data);
1400 }
1401
1402 /// @TODO move to top of file or somewhere better
1403 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1404
1405 /**
1406  * Returns the most recent statuses posted by users this node knows about.
1407  *
1408  * @param string $type Return format: json, xml, atom, rss
1409  * @return array|string
1410  * @throws BadRequestException
1411  * @throws ForbiddenException
1412  * @throws ImagickException
1413  * @throws InternalServerErrorException
1414  * @throws UnauthorizedException
1415  */
1416 function api_statuses_networkpublic_timeline($type)
1417 {
1418         $a = DI::app();
1419         $user_info = api_get_user();
1420
1421         if (api_user() === false || $user_info === false) {
1422                 throw new ForbiddenException();
1423         }
1424
1425         $since_id        = $_REQUEST['since_id'] ?? 0;
1426         $max_id          = $_REQUEST['max_id'] ?? 0;
1427
1428         // pagination
1429         $count = $_REQUEST['count'] ?? 20;
1430         $page  = $_REQUEST['page'] ?? 1;
1431
1432         $start = max(0, ($page - 1) * $count);
1433
1434         $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1435                 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1436
1437         if ($max_id > 0) {
1438                 $condition[0] .= " AND `id` <= ?";
1439                 $condition[] = $max_id;
1440         }
1441
1442         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1443         $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1444
1445         $ret = api_format_items($statuses, $user_info, false, $type);
1446
1447         bindComments($ret);
1448
1449         $data = ['status' => $ret];
1450         switch ($type) {
1451                 case "atom":
1452                         break;
1453                 case "rss":
1454                         $data = api_rss_extra($a, $data, $user_info);
1455                         break;
1456         }
1457
1458         return DI::apiResponse()->formatData("statuses", $type, $data);
1459 }
1460
1461 /// @TODO move to top of file or somewhere better
1462 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1463
1464 /**
1465  * Returns a single status.
1466  *
1467  * @param string $type Return type (atom, rss, xml, json)
1468  *
1469  * @return array|string
1470  * @throws BadRequestException
1471  * @throws ForbiddenException
1472  * @throws ImagickException
1473  * @throws InternalServerErrorException
1474  * @throws UnauthorizedException
1475  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1476  */
1477 function api_statuses_show($type)
1478 {
1479         $a = DI::app();
1480         $user_info = api_get_user();
1481
1482         if (api_user() === false || $user_info === false) {
1483                 throw new ForbiddenException();
1484         }
1485
1486         // params
1487         $id = intval(DI::args()->getArgv()[3] ?? 0);
1488
1489         if ($id == 0) {
1490                 $id = intval($_REQUEST['id'] ?? 0);
1491         }
1492
1493         // Hotot workaround
1494         if ($id == 0) {
1495                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1496         }
1497
1498         logger::notice('API: api_statuses_show: ' . $id);
1499
1500         $conversation = !empty($_REQUEST['conversation']);
1501
1502         // try to fetch the item for the local user - or the public item, if there is no local one
1503         $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1504         if (!DBA::isResult($uri_item)) {
1505                 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1506         }
1507
1508         $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1509         if (!DBA::isResult($item)) {
1510                 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1511         }
1512
1513         $id = $item['id'];
1514
1515         if ($conversation) {
1516                 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1517                 $params = ['order' => ['id' => true]];
1518         } else {
1519                 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1520                 $params = [];
1521         }
1522
1523         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1524
1525         /// @TODO How about copying this to above methods which don't check $r ?
1526         if (!DBA::isResult($statuses)) {
1527                 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1528         }
1529
1530         $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1531
1532         if ($conversation) {
1533                 $data = ['status' => $ret];
1534                 return DI::apiResponse()->formatData("statuses", $type, $data);
1535         } else {
1536                 $data = ['status' => $ret[0]];
1537                 return DI::apiResponse()->formatData("status", $type, $data);
1538         }
1539 }
1540
1541 /// @TODO move to top of file or somewhere better
1542 api_register_func('api/statuses/show', 'api_statuses_show', true);
1543
1544 /**
1545  *
1546  * @param string $type Return type (atom, rss, xml, json)
1547  *
1548  * @return array|string
1549  * @throws BadRequestException
1550  * @throws ForbiddenException
1551  * @throws ImagickException
1552  * @throws InternalServerErrorException
1553  * @throws UnauthorizedException
1554  * @todo nothing to say?
1555  */
1556 function api_conversation_show($type)
1557 {
1558         $a = DI::app();
1559         $user_info = api_get_user();
1560
1561         if (api_user() === false || $user_info === false) {
1562                 throw new ForbiddenException();
1563         }
1564
1565         // params
1566         $id       = intval(DI::args()->getArgv()[3]           ?? 0);
1567         $since_id = intval($_REQUEST['since_id'] ?? 0);
1568         $max_id   = intval($_REQUEST['max_id']   ?? 0);
1569         $count    = intval($_REQUEST['count']    ?? 20);
1570         $page     = intval($_REQUEST['page']     ?? 1);
1571
1572         $start = max(0, ($page - 1) * $count);
1573
1574         if ($id == 0) {
1575                 $id = intval($_REQUEST['id'] ?? 0);
1576         }
1577
1578         // Hotot workaround
1579         if ($id == 0) {
1580                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1581         }
1582
1583         Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1584
1585         // try to fetch the item for the local user - or the public item, if there is no local one
1586         $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1587         if (!DBA::isResult($item)) {
1588                 throw new BadRequestException("There is no status with the id $id.");
1589         }
1590
1591         $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1592         if (!DBA::isResult($parent)) {
1593                 throw new BadRequestException("There is no status with this id.");
1594         }
1595
1596         $id = $parent['id'];
1597
1598         $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1599                 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1600
1601         if ($max_id > 0) {
1602                 $condition[0] .= " AND `id` <= ?";
1603                 $condition[] = $max_id;
1604         }
1605
1606         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1607         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1608
1609         if (!DBA::isResult($statuses)) {
1610                 throw new BadRequestException("There is no status with id $id.");
1611         }
1612
1613         $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1614
1615         $data = ['status' => $ret];
1616         return DI::apiResponse()->formatData("statuses", $type, $data);
1617 }
1618
1619 /// @TODO move to top of file or somewhere better
1620 api_register_func('api/conversation/show', 'api_conversation_show', true);
1621 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1622
1623 /**
1624  * Repeats a status.
1625  *
1626  * @param string $type Return type (atom, rss, xml, json)
1627  *
1628  * @return array|string
1629  * @throws BadRequestException
1630  * @throws ForbiddenException
1631  * @throws ImagickException
1632  * @throws InternalServerErrorException
1633  * @throws UnauthorizedException
1634  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1635  */
1636 function api_statuses_repeat($type)
1637 {
1638         global $called_api;
1639
1640         $a = DI::app();
1641
1642         if (api_user() === false) {
1643                 throw new ForbiddenException();
1644         }
1645
1646         api_get_user();
1647
1648         // params
1649         $id = intval(DI::args()->getArgv()[3] ?? 0);
1650
1651         if ($id == 0) {
1652                 $id = intval($_REQUEST['id'] ?? 0);
1653         }
1654
1655         // Hotot workaround
1656         if ($id == 0) {
1657                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1658         }
1659
1660         logger::notice('API: api_statuses_repeat: ' . $id);
1661
1662         $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1663         $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1664
1665         if (DBA::isResult($item) && !empty($item['body'])) {
1666                 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1667                         if (!Item::performActivity($id, 'announce', local_user())) {
1668                                 throw new InternalServerErrorException();
1669                         }
1670
1671                         $item_id = $id;
1672                 } else {
1673                         if (strpos($item['body'], "[/share]") !== false) {
1674                                 $pos = strpos($item['body'], "[share");
1675                                 $post = substr($item['body'], $pos);
1676                         } else {
1677                                 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1678
1679                                 if (!empty($item['title'])) {
1680                                         $post .= '[h3]' . $item['title'] . "[/h3]\n";
1681                                 }
1682
1683                                 $post .= $item['body'];
1684                                 $post .= "[/share]";
1685                         }
1686                         $_REQUEST['body'] = $post;
1687                         $_REQUEST['profile_uid'] = api_user();
1688                         $_REQUEST['api_source'] = true;
1689
1690                         if (empty($_REQUEST['source'])) {
1691                                 $_REQUEST["source"] = api_source();
1692                         }
1693
1694                         $item_id = item_post($a);
1695                 }
1696         } else {
1697                 throw new ForbiddenException();
1698         }
1699
1700         // output the post that we just posted.
1701         $called_api = [];
1702         return api_status_show($type, $item_id);
1703 }
1704
1705 /// @TODO move to top of file or somewhere better
1706 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1707
1708 /**
1709  * Destroys a specific status.
1710  *
1711  * @param string $type Return type (atom, rss, xml, json)
1712  *
1713  * @return array|string
1714  * @throws BadRequestException
1715  * @throws ForbiddenException
1716  * @throws ImagickException
1717  * @throws InternalServerErrorException
1718  * @throws UnauthorizedException
1719  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1720  */
1721 function api_statuses_destroy($type)
1722 {
1723         $a = DI::app();
1724
1725         if (api_user() === false) {
1726                 throw new ForbiddenException();
1727         }
1728
1729         api_get_user();
1730
1731         // params
1732         $id = intval(DI::args()->getArgv()[3] ?? 0);
1733
1734         if ($id == 0) {
1735                 $id = intval($_REQUEST['id'] ?? 0);
1736         }
1737
1738         // Hotot workaround
1739         if ($id == 0) {
1740                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1741         }
1742
1743         logger::notice('API: api_statuses_destroy: ' . $id);
1744
1745         $ret = api_statuses_show($type);
1746
1747         Item::deleteForUser(['id' => $id], api_user());
1748
1749         return $ret;
1750 }
1751
1752 /// @TODO move to top of file or somewhere better
1753 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1754
1755 /**
1756  * Returns the most recent mentions.
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 http://developer.twitter.com/doc/get/statuses/mentions
1767  */
1768 function api_statuses_mentions($type)
1769 {
1770         $a = DI::app();
1771         $user_info = api_get_user();
1772
1773         if (api_user() === false || $user_info === false) {
1774                 throw new ForbiddenException();
1775         }
1776
1777         unset($_REQUEST["user_id"]);
1778         unset($_GET["user_id"]);
1779
1780         unset($_REQUEST["screen_name"]);
1781         unset($_GET["screen_name"]);
1782
1783         // get last network messages
1784
1785         // params
1786         $since_id = intval($_REQUEST['since_id'] ?? 0);
1787         $max_id   = intval($_REQUEST['max_id']   ?? 0);
1788         $count    = intval($_REQUEST['count']    ?? 20);
1789         $page     = intval($_REQUEST['page']     ?? 1);
1790
1791         $start = max(0, ($page - 1) * $count);
1792
1793         $query = "`gravity` IN (?, ?) AND `uri-id` IN
1794                 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1795                 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1796
1797         $condition = [
1798                 GRAVITY_PARENT, GRAVITY_COMMENT,
1799                 api_user(),
1800                 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1801                 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1802                 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1803                 api_user(), $since_id,
1804         ];
1805
1806         if ($max_id > 0) {
1807                 $query .= " AND `id` <= ?";
1808                 $condition[] = $max_id;
1809         }
1810
1811         array_unshift($condition, $query);
1812
1813         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1814         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1815
1816         $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1817
1818         $data = ['status' => $ret];
1819         switch ($type) {
1820                 case "atom":
1821                         break;
1822                 case "rss":
1823                         $data = api_rss_extra($a, $data, $user_info);
1824                         break;
1825         }
1826
1827         return DI::apiResponse()->formatData("statuses", $type, $data);
1828 }
1829
1830 /// @TODO move to top of file or somewhere better
1831 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1832 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1833
1834 /**
1835  * Returns the most recent statuses posted by the user.
1836  *
1837  * @param string $type Either "json" or "xml"
1838  * @return string|array
1839  * @throws BadRequestException
1840  * @throws ForbiddenException
1841  * @throws ImagickException
1842  * @throws InternalServerErrorException
1843  * @throws UnauthorizedException
1844  * @see   https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1845  */
1846 function api_statuses_user_timeline($type)
1847 {
1848         $a = DI::app();
1849         $user_info = api_get_user();
1850
1851         if (api_user() === false || $user_info === false) {
1852                 throw new ForbiddenException();
1853         }
1854
1855         Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
1856
1857         $since_id        = $_REQUEST['since_id'] ?? 0;
1858         $max_id          = $_REQUEST['max_id'] ?? 0;
1859         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1860         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1861
1862         // pagination
1863         $count = $_REQUEST['count'] ?? 20;
1864         $page  = $_REQUEST['page'] ?? 1;
1865
1866         $start = max(0, ($page - 1) * $count);
1867
1868         $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
1869                 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
1870
1871         if ($user_info['self'] == 1) {
1872                 $condition[0] .= ' AND `wall` ';
1873         }
1874
1875         if ($exclude_replies) {
1876                 $condition[0] .= ' AND `gravity` = ?';
1877                 $condition[] = GRAVITY_PARENT;
1878         }
1879
1880         if ($conversation_id > 0) {
1881                 $condition[0] .= " AND `parent` = ?";
1882                 $condition[] = $conversation_id;
1883         }
1884
1885         if ($max_id > 0) {
1886                 $condition[0] .= " AND `id` <= ?";
1887                 $condition[] = $max_id;
1888         }
1889         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1890         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1891
1892         $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
1893
1894         bindComments($ret);
1895
1896         $data = ['status' => $ret];
1897         switch ($type) {
1898                 case "atom":
1899                         break;
1900                 case "rss":
1901                         $data = api_rss_extra($a, $data, $user_info);
1902                         break;
1903         }
1904
1905         return DI::apiResponse()->formatData("statuses", $type, $data);
1906 }
1907
1908 /// @TODO move to top of file or somewhere better
1909 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1910
1911 /**
1912  * Star/unstar an item.
1913  * param: id : id of the item
1914  *
1915  * @param string $type Return type (atom, rss, xml, json)
1916  *
1917  * @return array|string
1918  * @throws BadRequestException
1919  * @throws ForbiddenException
1920  * @throws ImagickException
1921  * @throws InternalServerErrorException
1922  * @throws UnauthorizedException
1923  * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1924  */
1925 function api_favorites_create_destroy($type)
1926 {
1927         $a = DI::app();
1928
1929         if (api_user() === false) {
1930                 throw new ForbiddenException();
1931         }
1932
1933         // for versioned api.
1934         /// @TODO We need a better global soluton
1935         $action_argv_id = 2;
1936         if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1937                 $action_argv_id = 3;
1938         }
1939
1940         if (DI::args()->getArgc() <= $action_argv_id) {
1941                 throw new BadRequestException("Invalid request.");
1942         }
1943         $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1944         if (DI::args()->getArgc() == $action_argv_id + 2) {
1945                 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1946         } else {
1947                 $itemid = intval($_REQUEST['id'] ?? 0);
1948         }
1949
1950         $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
1951
1952         if (!DBA::isResult($item)) {
1953                 throw new BadRequestException("Invalid item.");
1954         }
1955
1956         switch ($action) {
1957                 case "create":
1958                         $item['starred'] = 1;
1959                         break;
1960                 case "destroy":
1961                         $item['starred'] = 0;
1962                         break;
1963                 default:
1964                         throw new BadRequestException("Invalid action ".$action);
1965         }
1966
1967         $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1968
1969         if ($r === false) {
1970                 throw new InternalServerErrorException("DB error");
1971         }
1972
1973
1974         $user_info = api_get_user();
1975         $rets = api_format_items([$item], $user_info, false, $type);
1976         $ret = $rets[0];
1977
1978         $data = ['status' => $ret];
1979         switch ($type) {
1980                 case "atom":
1981                         break;
1982                 case "rss":
1983                         $data = api_rss_extra($a, $data, $user_info);
1984                         break;
1985         }
1986
1987         return DI::apiResponse()->formatData("status", $type, $data);
1988 }
1989
1990 /// @TODO move to top of file or somewhere better
1991 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1992 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1993
1994 /**
1995  * Returns the most recent favorite statuses.
1996  *
1997  * @param string $type Return type (atom, rss, xml, json)
1998  *
1999  * @return string|array
2000  * @throws BadRequestException
2001  * @throws ForbiddenException
2002  * @throws ImagickException
2003  * @throws InternalServerErrorException
2004  * @throws UnauthorizedException
2005  */
2006 function api_favorites($type)
2007 {
2008         global $called_api;
2009
2010         $a = DI::app();
2011         $user_info = api_get_user();
2012
2013         if (api_user() === false || $user_info === false) {
2014                 throw new ForbiddenException();
2015         }
2016
2017         $called_api = [];
2018
2019         // in friendica starred item are private
2020         // return favorites only for self
2021         Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2022
2023         if ($user_info['self'] == 0) {
2024                 $ret = [];
2025         } else {
2026                 // params
2027                 $since_id = $_REQUEST['since_id'] ?? 0;
2028                 $max_id = $_REQUEST['max_id'] ?? 0;
2029                 $count = $_GET['count'] ?? 20;
2030                 $page = $_REQUEST['page'] ?? 1;
2031
2032                 $start = max(0, ($page - 1) * $count);
2033
2034                 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2035                         api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2036
2037                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2038
2039                 if ($max_id > 0) {
2040                         $condition[0] .= " AND `id` <= ?";
2041                         $condition[] = $max_id;
2042                 }
2043
2044                 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2045
2046                 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2047         }
2048
2049         bindComments($ret);
2050
2051         $data = ['status' => $ret];
2052         switch ($type) {
2053                 case "atom":
2054                         break;
2055                 case "rss":
2056                         $data = api_rss_extra($a, $data, $user_info);
2057                         break;
2058         }
2059
2060         return DI::apiResponse()->formatData("statuses", $type, $data);
2061 }
2062
2063 /// @TODO move to top of file or somewhere better
2064 api_register_func('api/favorites', 'api_favorites', true);
2065
2066 /**
2067  *
2068  * @param array $item
2069  * @param array $recipient
2070  * @param array $sender
2071  *
2072  * @return array
2073  * @throws InternalServerErrorException
2074  */
2075 function api_format_messages($item, $recipient, $sender)
2076 {
2077         // standard meta information
2078         $ret = [
2079                 'id'                    => $item['id'],
2080                 'sender_id'             => $sender['id'],
2081                 'text'                  => "",
2082                 'recipient_id'          => $recipient['id'],
2083                 'created_at'            => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2084                 'sender_screen_name'    => $sender['screen_name'],
2085                 'recipient_screen_name' => $recipient['screen_name'],
2086                 'sender'                => $sender,
2087                 'recipient'             => $recipient,
2088                 'title'                 => "",
2089                 'friendica_seen'        => $item['seen'] ?? 0,
2090                 'friendica_parent_uri'  => $item['parent-uri'] ?? '',
2091         ];
2092
2093         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2094         if (isset($ret['sender']['uid'])) {
2095                 unset($ret['sender']['uid']);
2096         }
2097         if (isset($ret['sender']['self'])) {
2098                 unset($ret['sender']['self']);
2099         }
2100         if (isset($ret['recipient']['uid'])) {
2101                 unset($ret['recipient']['uid']);
2102         }
2103         if (isset($ret['recipient']['self'])) {
2104                 unset($ret['recipient']['self']);
2105         }
2106
2107         //don't send title to regular StatusNET requests to avoid confusing these apps
2108         if (!empty($_GET['getText'])) {
2109                 $ret['title'] = $item['title'];
2110                 if ($_GET['getText'] == 'html') {
2111                         $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
2112                 } elseif ($_GET['getText'] == 'plain') {
2113                         $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
2114                 }
2115         } else {
2116                 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
2117         }
2118         if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2119                 unset($ret['sender']);
2120                 unset($ret['recipient']);
2121         }
2122
2123         return $ret;
2124 }
2125
2126 /**
2127  *
2128  * @param array $item
2129  *
2130  * @return array
2131  * @throws InternalServerErrorException
2132  */
2133 function api_convert_item($item)
2134 {
2135         $body = api_add_attachments_to_body($item);
2136
2137         $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2138
2139         // Add pictures to the attachment array and remove them from the body
2140         $attachments = api_get_attachments($body, $item['uri-id']);
2141
2142         // Workaround for ostatus messages where the title is identically to the body
2143         $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
2144         $statusbody = trim(HTML::toPlaintext($html, 0));
2145
2146         // handle data: images
2147         $statusbody = api_format_items_embeded_images($item, $statusbody);
2148
2149         $statustitle = trim($item['title']);
2150
2151         if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2152                 $statustext = trim($statusbody);
2153         } else {
2154                 $statustext = trim($statustitle."\n\n".$statusbody);
2155         }
2156
2157         if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2158                 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2159         }
2160
2161         $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2162
2163         // Workaround for clients with limited HTML parser functionality
2164         $search = ["<br>", "<blockquote>", "</blockquote>",
2165                         "<h1>", "</h1>", "<h2>", "</h2>",
2166                         "<h3>", "</h3>", "<h4>", "</h4>",
2167                         "<h5>", "</h5>", "<h6>", "</h6>"];
2168         $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2169                         "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2170                         "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2171                         "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2172         $statushtml = str_replace($search, $replace, $statushtml);
2173
2174         if ($item['title'] != "") {
2175                 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2176         }
2177
2178         do {
2179                 $oldtext = $statushtml;
2180                 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2181         } while ($oldtext != $statushtml);
2182
2183         if (substr($statushtml, 0, 4) == '<br>') {
2184                 $statushtml = substr($statushtml, 4);
2185         }
2186
2187         if (substr($statushtml, 0, -4) == '<br>') {
2188                 $statushtml = substr($statushtml, -4);
2189         }
2190
2191         // feeds without body should contain the link
2192         if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2193                 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2194         }
2195
2196         return [
2197                 "text" => $statustext,
2198                 "html" => $statushtml,
2199                 "attachments" => $attachments,
2200                 "entities" => $entities
2201         ];
2202 }
2203
2204 /**
2205  * Add media attachments to the body
2206  *
2207  * @param array $item
2208  * @return string body with added media
2209  */
2210 function api_add_attachments_to_body(array $item)
2211 {
2212         $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2213
2214         if (strpos($body, '[/img]') !== false) {
2215                 return $body;
2216         }
2217
2218         foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2219                 if (!empty($media['preview'])) {
2220                         $description = $media['description'] ?: $media['name'];
2221                         if (!empty($description)) {
2222                                 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2223                         } else {
2224                                 $body .= "\n[img]" . $media['preview'] .'[/img]';
2225                         }
2226                 }
2227         }
2228
2229         return $body;
2230 }
2231
2232 /**
2233  *
2234  * @param string $body
2235  * @param int    $uriid
2236  *
2237  * @return array
2238  * @throws InternalServerErrorException
2239  */
2240 function api_get_attachments(&$body, $uriid)
2241 {
2242         $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2243         $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2244
2245         $URLSearchString = "^\[\]";
2246         if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2247                 return [];
2248         }
2249
2250         // Remove all embedded pictures, since they are added as attachments
2251         foreach ($images[0] as $orig) {
2252                 $body = str_replace($orig, '', $body);
2253         }
2254
2255         $attachments = [];
2256
2257         foreach ($images[1] as $image) {
2258                 $imagedata = Images::getInfoFromURLCached($image);
2259
2260                 if ($imagedata) {
2261                         $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2262                 }
2263         }
2264
2265         return $attachments;
2266 }
2267
2268 /**
2269  *
2270  * @param string $text
2271  * @param string $bbcode
2272  *
2273  * @return array
2274  * @throws InternalServerErrorException
2275  * @todo Links at the first character of the post
2276  */
2277 function api_get_entitities(&$text, $bbcode, $uriid)
2278 {
2279         $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2280
2281         if ($include_entities != "true") {
2282                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2283
2284                 foreach ($images[1] as $image) {
2285                         $replace = Post\Link::getByLink($uriid, $image);
2286                         $text = str_replace($image, $replace, $text);
2287                 }
2288                 return [];
2289         }
2290
2291         $bbcode = BBCode::cleanPictureLinks($bbcode);
2292
2293         // Change pure links in text to bbcode uris
2294         $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2295
2296         $entities = [];
2297         $entities["hashtags"] = [];
2298         $entities["symbols"] = [];
2299         $entities["urls"] = [];
2300         $entities["user_mentions"] = [];
2301
2302         $URLSearchString = "^\[\]";
2303
2304         $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2305
2306         $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2307         $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2308
2309         $bbcode = preg_replace(
2310                 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2311                 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2312                 $bbcode
2313         );
2314         $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2315
2316         $bbcode = preg_replace(
2317                 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2318                 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2319                 $bbcode
2320         );
2321         $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2322
2323         $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2324
2325         preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2326
2327         $ordered_urls = [];
2328         foreach ($urls[1] as $id => $url) {
2329                 $start = iconv_strpos($text, $url, 0, "UTF-8");
2330                 if (!($start === false)) {
2331                         $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2332                 }
2333         }
2334
2335         ksort($ordered_urls);
2336
2337         $offset = 0;
2338
2339         foreach ($ordered_urls as $url) {
2340                 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2341                         && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2342                 ) {
2343                         $display_url = $url["title"];
2344                 } else {
2345                         $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2346                         $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2347
2348                         if (strlen($display_url) > 26) {
2349                                 $display_url = substr($display_url, 0, 25)."…";
2350                         }
2351                 }
2352
2353                 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2354                 if (!($start === false)) {
2355                         $entities["urls"][] = ["url" => $url["url"],
2356                                                         "expanded_url" => $url["url"],
2357                                                         "display_url" => $display_url,
2358                                                         "indices" => [$start, $start+strlen($url["url"])]];
2359                         $offset = $start + 1;
2360                 }
2361         }
2362
2363         preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2364         $ordered_images = [];
2365         foreach ($images as $image) {
2366                 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2367                 if (!($start === false)) {
2368                         $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2369                 }
2370         }
2371
2372         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2373         foreach ($images[1] as $image) {
2374                 $start = iconv_strpos($text, $image, 0, "UTF-8");
2375                 if (!($start === false)) {
2376                         $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2377                 }
2378         }
2379
2380         $offset = 0;
2381
2382         foreach ($ordered_images as $image) {
2383                 $url = $image['url'];
2384                 $ext_alt_text = $image['alt'];
2385
2386                 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2387                 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2388
2389                 if (strlen($display_url) > 26) {
2390                         $display_url = substr($display_url, 0, 25)."…";
2391                 }
2392
2393                 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2394                 if (!($start === false)) {
2395                         $image = Images::getInfoFromURLCached($url);
2396                         if ($image) {
2397                                 $media_url = Post\Link::getByLink($uriid, $url);
2398                                 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2399
2400                                 $entities["media"][] = [
2401                                                         "id" => $start+1,
2402                                                         "id_str" => (string) ($start + 1),
2403                                                         "indices" => [$start, $start+strlen($url)],
2404                                                         "media_url" => Strings::normaliseLink($media_url),
2405                                                         "media_url_https" => $media_url,
2406                                                         "url" => $url,
2407                                                         "display_url" => $display_url,
2408                                                         "expanded_url" => $url,
2409                                                         "ext_alt_text" => $ext_alt_text,
2410                                                         "type" => "photo",
2411                                                         "sizes" => $sizes];
2412                         }
2413                         $offset = $start + 1;
2414                 }
2415         }
2416
2417         return $entities;
2418 }
2419
2420 /**
2421  *
2422  * @param array $item
2423  * @param string $text
2424  *
2425  * @return string
2426  */
2427 function api_format_items_embeded_images($item, $text)
2428 {
2429         $text = preg_replace_callback(
2430                 '|data:image/([^;]+)[^=]+=*|m',
2431                 function () use ($item) {
2432                         return DI::baseUrl() . '/display/' . $item['guid'];
2433                 },
2434                 $text
2435         );
2436         return $text;
2437 }
2438
2439 /**
2440  * return <a href='url'>name</a> as array
2441  *
2442  * @param string $txt text
2443  * @return array
2444  *                      'name' => 'name',
2445  *                      'url => 'url'
2446  */
2447 function api_contactlink_to_array($txt)
2448 {
2449         $match = [];
2450         $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2451         if ($r && count($match)==3) {
2452                 $res = [
2453                         'name' => $match[2],
2454                         'url' => $match[1]
2455                 ];
2456         } else {
2457                 $res = [
2458                         'name' => $txt,
2459                         'url' => ""
2460                 ];
2461         }
2462         return $res;
2463 }
2464
2465
2466 /**
2467  * return likes, dislikes and attend status for item
2468  *
2469  * @param array  $item array
2470  * @param string $type Return type (atom, rss, xml, json)
2471  *
2472  * @return array
2473  *            likes => int count,
2474  *            dislikes => int count
2475  * @throws BadRequestException
2476  * @throws ImagickException
2477  * @throws InternalServerErrorException
2478  * @throws UnauthorizedException
2479  */
2480 function api_format_items_activities($item, $type = "json")
2481 {
2482         $a = DI::app();
2483
2484         $activities = [
2485                 'like' => [],
2486                 'dislike' => [],
2487                 'attendyes' => [],
2488                 'attendno' => [],
2489                 'attendmaybe' => [],
2490                 'announce' => [],
2491         ];
2492
2493         $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2494         $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2495
2496         while ($parent_item = Post::fetch($ret)) {
2497                 // not used as result should be structured like other user data
2498                 //builtin_activity_puller($i, $activities);
2499
2500                 // get user data and add it to the array of the activity
2501                 $user = api_get_user($parent_item['author-id']);
2502                 switch ($parent_item['verb']) {
2503                         case Activity::LIKE:
2504                                 $activities['like'][] = $user;
2505                                 break;
2506                         case Activity::DISLIKE:
2507                                 $activities['dislike'][] = $user;
2508                                 break;
2509                         case Activity::ATTEND:
2510                                 $activities['attendyes'][] = $user;
2511                                 break;
2512                         case Activity::ATTENDNO:
2513                                 $activities['attendno'][] = $user;
2514                                 break;
2515                         case Activity::ATTENDMAYBE:
2516                                 $activities['attendmaybe'][] = $user;
2517                                 break;
2518                         case Activity::ANNOUNCE:
2519                                 $activities['announce'][] = $user;
2520                                 break;
2521                         default:
2522                                 break;
2523                 }
2524         }
2525
2526         DBA::close($ret);
2527
2528         if ($type == "xml") {
2529                 $xml_activities = [];
2530                 foreach ($activities as $k => $v) {
2531                         // change xml element from "like" to "friendica:like"
2532                         $xml_activities["friendica:".$k] = $v;
2533                         // add user data into xml output
2534                         $k_user = 0;
2535                         foreach ($v as $user) {
2536                                 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2537                         }
2538                 }
2539                 $activities = $xml_activities;
2540         }
2541
2542         return $activities;
2543 }
2544
2545 /**
2546  * format items to be returned by api
2547  *
2548  * @param array  $items       array of items
2549  * @param array  $user_info
2550  * @param bool   $filter_user filter items by $user_info
2551  * @param string $type        Return type (atom, rss, xml, json)
2552  * @return array
2553  * @throws BadRequestException
2554  * @throws ImagickException
2555  * @throws InternalServerErrorException
2556  * @throws UnauthorizedException
2557  */
2558 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2559 {
2560         $a = Friendica\DI::app();
2561
2562         $ret = [];
2563
2564         if (empty($items)) {
2565                 return $ret;
2566         }
2567
2568         foreach ((array)$items as $item) {
2569                 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2570
2571                 // Look if the posts are matching if they should be filtered by user id
2572                 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2573                         continue;
2574                 }
2575
2576                 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2577
2578                 $ret[] = $status;
2579         }
2580
2581         return $ret;
2582 }
2583
2584 /**
2585  * @param array  $item       Item record
2586  * @param string $type       Return format (atom, rss, xml, json)
2587  * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2588  * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2589  * @param array $owner_user  User record of the item owner, can be provided by api_item_get_user()
2590  * @return array API-formatted status
2591  * @throws BadRequestException
2592  * @throws ImagickException
2593  * @throws InternalServerErrorException
2594  * @throws UnauthorizedException
2595  */
2596 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2597 {
2598         $a = Friendica\DI::app();
2599
2600         if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2601                 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2602         }
2603
2604         DI::contentItem()->localize($item);
2605
2606         $in_reply_to = api_in_reply_to($item);
2607
2608         $converted = api_convert_item($item);
2609
2610         if ($type == "xml") {
2611                 $geo = "georss:point";
2612         } else {
2613                 $geo = "geo";
2614         }
2615
2616         $status = [
2617                 'text'          => $converted["text"],
2618                 'truncated' => false,
2619                 'created_at'=> api_date($item['created']),
2620                 'in_reply_to_status_id' => $in_reply_to['status_id'],
2621                 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2622                 'source'    => (($item['app']) ? $item['app'] : 'web'),
2623                 'id'            => intval($item['id']),
2624                 'id_str'        => (string) intval($item['id']),
2625                 'in_reply_to_user_id' => $in_reply_to['user_id'],
2626                 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2627                 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2628                 $geo => null,
2629                 'favorited' => $item['starred'] ? true : false,
2630                 'user' =>  $status_user,
2631                 'friendica_author' => $author_user,
2632                 'friendica_owner' => $owner_user,
2633                 'friendica_private' => $item['private'] == Item::PRIVATE,
2634                 //'entities' => NULL,
2635                 'statusnet_html' => $converted["html"],
2636                 'statusnet_conversation_id' => $item['parent'],
2637                 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2638                 'friendica_activities' => api_format_items_activities($item, $type),
2639                 'friendica_title' => $item['title'],
2640                 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
2641         ];
2642
2643         if (count($converted["attachments"]) > 0) {
2644                 $status["attachments"] = $converted["attachments"];
2645         }
2646
2647         if (count($converted["entities"]) > 0) {
2648                 $status["entities"] = $converted["entities"];
2649         }
2650
2651         if ($status["source"] == 'web') {
2652                 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2653         } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2654                 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2655         }
2656
2657         $retweeted_item = [];
2658         $quoted_item = [];
2659
2660         if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2661                 $announce = api_get_announce($item);
2662                 if (!empty($announce)) {
2663                         $retweeted_item = $item;
2664                         $item = $announce;
2665                         $status['friendica_owner'] = api_get_user($announce['author-id']);
2666                 }
2667         }
2668
2669         if (!empty($quoted_item)) {
2670                 if ($quoted_item['id'] != $item['id']) {
2671                         $quoted_status = api_format_item($quoted_item);
2672                         /// @todo Only remove the attachments that are also contained in the quotes status
2673                         unset($status['attachments']);
2674                         unset($status['entities']);
2675                 } else {
2676                         $conv_quoted = api_convert_item($quoted_item);
2677                         $quoted_status = $status;
2678                         unset($quoted_status['attachments']);
2679                         unset($quoted_status['entities']);
2680                         unset($quoted_status['statusnet_conversation_id']);
2681                         $quoted_status['text'] = $conv_quoted['text'];
2682                         $quoted_status['statusnet_html'] = $conv_quoted['html'];
2683                         try {
2684                                 $quoted_status["user"] = api_get_user($quoted_item["author-id"]);
2685                         } catch (BadRequestException $e) {
2686                                 // user not found. should be found?
2687                                 /// @todo check if the user should be always found
2688                                 $quoted_status["user"] = [];
2689                         }
2690                 }
2691                 unset($quoted_status['friendica_author']);
2692                 unset($quoted_status['friendica_owner']);
2693                 unset($quoted_status['friendica_activities']);
2694                 unset($quoted_status['friendica_private']);
2695         }
2696
2697         if (!empty($retweeted_item)) {
2698                 $retweeted_status = $status;
2699                 unset($retweeted_status['friendica_author']);
2700                 unset($retweeted_status['friendica_owner']);
2701                 unset($retweeted_status['friendica_activities']);
2702                 unset($retweeted_status['friendica_private']);
2703                 unset($retweeted_status['statusnet_conversation_id']);
2704                 $status['user'] = $status['friendica_owner'];
2705                 try {
2706                         $retweeted_status["user"] = api_get_user($retweeted_item["author-id"]);
2707                 } catch (BadRequestException $e) {
2708                         // user not found. should be found?
2709                         /// @todo check if the user should be always found
2710                         $retweeted_status["user"] = [];
2711                 }
2712
2713                 $rt_converted = api_convert_item($retweeted_item);
2714
2715                 $retweeted_status['text'] = $rt_converted["text"];
2716                 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2717                 $retweeted_status['friendica_html'] = $rt_converted["html"];
2718                 $retweeted_status['created_at'] =  api_date($retweeted_item['created']);
2719
2720                 if (!empty($quoted_status)) {
2721                         $retweeted_status['quoted_status'] = $quoted_status;
2722                 }
2723
2724                 $status['friendica_author'] = $retweeted_status['user'];
2725                 $status['retweeted_status'] = $retweeted_status;
2726         } elseif (!empty($quoted_status)) {
2727                 $root_status = api_convert_item($item);
2728
2729                 $status['text'] = $root_status["text"];
2730                 $status['statusnet_html'] = $root_status["html"];
2731                 $status['quoted_status'] = $quoted_status;
2732         }
2733
2734         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2735         unset($status["user"]["uid"]);
2736         unset($status["user"]["self"]);
2737
2738         if ($item["coord"] != "") {
2739                 $coords = explode(' ', $item["coord"]);
2740                 if (count($coords) == 2) {
2741                         if ($type == "json") {
2742                                 $status["geo"] = ['type' => 'Point',
2743                                         'coordinates' => [(float) $coords[0],
2744                                                 (float) $coords[1]]];
2745                         } else {// Not sure if this is the official format - if someone founds a documentation we can check
2746                                 $status["georss:point"] = $item["coord"];
2747                         }
2748                 }
2749         }
2750
2751         return $status;
2752 }
2753
2754 /**
2755  * Returns all lists the user subscribes to.
2756  *
2757  * @param string $type Return type (atom, rss, xml, json)
2758  *
2759  * @return array|string
2760  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2761  */
2762 function api_lists_list($type)
2763 {
2764         $ret = [];
2765         /// @TODO $ret is not filled here?
2766         return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2767 }
2768
2769 /// @TODO move to top of file or somewhere better
2770 api_register_func('api/lists/list', 'api_lists_list', true);
2771 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2772
2773 /**
2774  * Returns all groups the user owns.
2775  *
2776  * @param string $type Return type (atom, rss, xml, json)
2777  *
2778  * @return array|string
2779  * @throws BadRequestException
2780  * @throws ForbiddenException
2781  * @throws ImagickException
2782  * @throws InternalServerErrorException
2783  * @throws UnauthorizedException
2784  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2785  */
2786 function api_lists_ownerships($type)
2787 {
2788         $a = DI::app();
2789
2790         if (api_user() === false) {
2791                 throw new ForbiddenException();
2792         }
2793
2794         // params
2795         $user_info = api_get_user();
2796         $uid = $user_info['uid'];
2797
2798         $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2799
2800         // loop through all groups
2801         $lists = [];
2802         foreach ($groups as $group) {
2803                 if ($group['visible']) {
2804                         $mode = 'public';
2805                 } else {
2806                         $mode = 'private';
2807                 }
2808                 $lists[] = [
2809                         'name' => $group['name'],
2810                         'id' => intval($group['id']),
2811                         'id_str' => (string) $group['id'],
2812                         'user' => $user_info,
2813                         'mode' => $mode
2814                 ];
2815         }
2816         return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2817 }
2818
2819 /// @TODO move to top of file or somewhere better
2820 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2821
2822 /**
2823  * Returns recent statuses from users in the specified group.
2824  *
2825  * @param string $type Return type (atom, rss, xml, json)
2826  *
2827  * @return array|string
2828  * @throws BadRequestException
2829  * @throws ForbiddenException
2830  * @throws ImagickException
2831  * @throws InternalServerErrorException
2832  * @throws UnauthorizedException
2833  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2834  */
2835 function api_lists_statuses($type)
2836 {
2837         $a = DI::app();
2838
2839         $user_info = api_get_user();
2840         if (api_user() === false || $user_info === false) {
2841                 throw new ForbiddenException();
2842         }
2843
2844         unset($_REQUEST["user_id"]);
2845         unset($_GET["user_id"]);
2846
2847         unset($_REQUEST["screen_name"]);
2848         unset($_GET["screen_name"]);
2849
2850         if (empty($_REQUEST['list_id'])) {
2851                 throw new BadRequestException('list_id not specified');
2852         }
2853
2854         // params
2855         $count = $_REQUEST['count'] ?? 20;
2856         $page = $_REQUEST['page'] ?? 1;
2857         $since_id = $_REQUEST['since_id'] ?? 0;
2858         $max_id = $_REQUEST['max_id'] ?? 0;
2859         $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2860         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2861
2862         $start = max(0, ($page - 1) * $count);
2863
2864         $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2865         $gids = array_column($groups, 'contact-id');
2866         $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2867         $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2868
2869         if ($max_id > 0) {
2870                 $condition[0] .= " AND `id` <= ?";
2871                 $condition[] = $max_id;
2872         }
2873         if ($exclude_replies > 0) {
2874                 $condition[0] .= ' AND `gravity` = ?';
2875                 $condition[] = GRAVITY_PARENT;
2876         }
2877         if ($conversation_id > 0) {
2878                 $condition[0] .= " AND `parent` = ?";
2879                 $condition[] = $conversation_id;
2880         }
2881
2882         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2883         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2884
2885         $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2886
2887         $data = ['status' => $items];
2888         switch ($type) {
2889                 case "atom":
2890                         break;
2891                 case "rss":
2892                         $data = api_rss_extra($a, $data, $user_info);
2893                         break;
2894         }
2895
2896         return DI::apiResponse()->formatData("statuses", $type, $data);
2897 }
2898
2899 /// @TODO move to top of file or somewhere better
2900 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2901
2902 /**
2903  * Returns either the friends of the follower list
2904  *
2905  * Considers friends and followers lists to be private and won't return
2906  * anything if any user_id parameter is passed.
2907  *
2908  * @param string $qtype Either "friends" or "followers"
2909  * @return boolean|array
2910  * @throws BadRequestException
2911  * @throws ForbiddenException
2912  * @throws ImagickException
2913  * @throws InternalServerErrorException
2914  * @throws UnauthorizedException
2915  */
2916 function api_statuses_f($qtype)
2917 {
2918         $a = DI::app();
2919
2920         if (api_user() === false) {
2921                 throw new ForbiddenException();
2922         }
2923
2924         // pagination
2925         $count = $_GET['count'] ?? 20;
2926         $page = $_GET['page'] ?? 1;
2927
2928         $start = max(0, ($page - 1) * $count);
2929
2930         $user_info = api_get_user();
2931
2932         if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2933                 /* this is to stop Hotot to load friends multiple times
2934                 *  I'm not sure if I'm missing return something or
2935                 *  is a bug in hotot. Workaround, meantime
2936                 */
2937
2938                 /*$ret=Array();
2939                 return array('$users' => $ret);*/
2940                 return false;
2941         }
2942
2943         $sql_extra = '';
2944         if ($qtype == 'friends') {
2945                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2946         } elseif ($qtype == 'followers') {
2947                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2948         }
2949
2950         // friends and followers only for self
2951         if ($user_info['self'] == 0) {
2952                 $sql_extra = " AND false ";
2953         }
2954
2955         if ($qtype == 'blocks') {
2956                 $sql_filter = 'AND `blocked` AND NOT `pending`';
2957         } elseif ($qtype == 'incoming') {
2958                 $sql_filter = 'AND `pending`';
2959         } else {
2960                 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2961         }
2962
2963         // @todo This query most likely can be replaced with a Contact::select...
2964         $r = DBA::toArray(DBA::p(
2965                 "SELECT `nurl`
2966                 FROM `contact`
2967                 WHERE `uid` = ?
2968                 AND NOT `self`
2969                 $sql_filter
2970                 $sql_extra
2971                 ORDER BY `nick`
2972                 LIMIT ?, ?",
2973                 api_user(),
2974                 $start,
2975                 $count
2976         ));
2977
2978         $ret = [];
2979         foreach ($r as $cid) {
2980                 $user = api_get_user($cid['nurl']);
2981                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2982                 unset($user["uid"]);
2983                 unset($user["self"]);
2984
2985                 if ($user) {
2986                         $ret[] = $user;
2987                 }
2988         }
2989
2990         return ['user' => $ret];
2991 }
2992
2993
2994 /**
2995  * Returns the list of friends of the provided user
2996  *
2997  * @deprecated By Twitter API in favor of friends/list
2998  *
2999  * @param string $type Either "json" or "xml"
3000  * @return boolean|string|array
3001  * @throws BadRequestException
3002  * @throws ForbiddenException
3003  */
3004 function api_statuses_friends($type)
3005 {
3006         $data =  api_statuses_f("friends");
3007         if ($data === false) {
3008                 return false;
3009         }
3010         return DI::apiResponse()->formatData("users", $type, $data);
3011 }
3012
3013 /**
3014  * Returns the list of followers of the provided user
3015  *
3016  * @deprecated By Twitter API in favor of friends/list
3017  *
3018  * @param string $type Either "json" or "xml"
3019  * @return boolean|string|array
3020  * @throws BadRequestException
3021  * @throws ForbiddenException
3022  */
3023 function api_statuses_followers($type)
3024 {
3025         $data = api_statuses_f("followers");
3026         if ($data === false) {
3027                 return false;
3028         }
3029         return DI::apiResponse()->formatData("users", $type, $data);
3030 }
3031
3032 /// @TODO move to top of file or somewhere better
3033 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3034 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3035
3036 /**
3037  * Returns the list of blocked users
3038  *
3039  * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3040  *
3041  * @param string $type Either "json" or "xml"
3042  *
3043  * @return boolean|string|array
3044  * @throws BadRequestException
3045  * @throws ForbiddenException
3046  */
3047 function api_blocks_list($type)
3048 {
3049         $data =  api_statuses_f('blocks');
3050         if ($data === false) {
3051                 return false;
3052         }
3053         return DI::apiResponse()->formatData("users", $type, $data);
3054 }
3055
3056 /// @TODO move to top of file or somewhere better
3057 api_register_func('api/blocks/list', 'api_blocks_list', true);
3058
3059 /**
3060  * Returns the list of pending users IDs
3061  *
3062  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3063  *
3064  * @param string $type Either "json" or "xml"
3065  *
3066  * @return boolean|string|array
3067  * @throws BadRequestException
3068  * @throws ForbiddenException
3069  */
3070 function api_friendships_incoming($type)
3071 {
3072         $data =  api_statuses_f('incoming');
3073         if ($data === false) {
3074                 return false;
3075         }
3076
3077         $ids = [];
3078         foreach ($data['user'] as $user) {
3079                 $ids[] = $user['id'];
3080         }
3081
3082         return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
3083 }
3084
3085 /// @TODO move to top of file or somewhere better
3086 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3087
3088 /**
3089  * Sends a new direct message.
3090  *
3091  * @param string $type Return type (atom, rss, xml, json)
3092  *
3093  * @return array|string
3094  * @throws BadRequestException
3095  * @throws ForbiddenException
3096  * @throws ImagickException
3097  * @throws InternalServerErrorException
3098  * @throws NotFoundException
3099  * @throws UnauthorizedException
3100  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3101  */
3102 function api_direct_messages_new($type)
3103 {
3104         $a = DI::app();
3105
3106         if (api_user() === false) {
3107                 throw new ForbiddenException();
3108         }
3109
3110         if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3111                 return;
3112         }
3113
3114         $sender = api_get_user();
3115
3116         $recipient = null;
3117         if (!empty($_POST['screen_name'])) {
3118                 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => api_user(), 'nick' => $_POST['screen_name']]);
3119                 if (DBA::isResult($contacts)) {
3120                         // Selecting the id by priority, friendica first
3121                         api_best_nickname($contacts);
3122
3123                         $recipient = api_get_user($contacts[0]['nurl']);
3124                 }
3125         } else {
3126                 $recipient = api_get_user($_POST['user_id']);
3127         }
3128
3129         if (empty($recipient)) {
3130                 throw new NotFoundException('Recipient not found');
3131         }
3132
3133         $replyto = '';
3134         if (!empty($_REQUEST['replyto'])) {
3135                 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => api_user(), 'id' => $_REQUEST['replyto']]);
3136                 $replyto = $mail['parent-uri'];
3137                 $sub     = $mail['title'];
3138         } else {
3139                 if (!empty($_REQUEST['title'])) {
3140                         $sub = $_REQUEST['title'];
3141                 } else {
3142                         $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3143                 }
3144         }
3145
3146         $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3147
3148         if ($id > -1) {
3149                 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
3150                 $ret = api_format_messages($mail, $recipient, $sender);
3151         } else {
3152                 $ret = ["error" => $id];
3153         }
3154
3155         $data = ['direct_message'=>$ret];
3156
3157         switch ($type) {
3158                 case "atom":
3159                         break;
3160                 case "rss":
3161                         $data = api_rss_extra($a, $data, $sender);
3162                         break;
3163         }
3164
3165         return DI::apiResponse()->formatData("direct-messages", $type, $data);
3166 }
3167
3168 /// @TODO move to top of file or somewhere better
3169 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3170
3171 /**
3172  * delete a direct_message from mail table through api
3173  *
3174  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3175  * @return string|array
3176  * @throws BadRequestException
3177  * @throws ForbiddenException
3178  * @throws ImagickException
3179  * @throws InternalServerErrorException
3180  * @throws UnauthorizedException
3181  * @see   https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3182  */
3183 function api_direct_messages_destroy($type)
3184 {
3185         $a = DI::app();
3186
3187         if (api_user() === false) {
3188                 throw new ForbiddenException();
3189         }
3190
3191         // params
3192         $user_info = api_get_user();
3193         //required
3194         $id = $_REQUEST['id'] ?? 0;
3195         // optional
3196         $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3197         $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3198         /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3199
3200         $uid = $user_info['uid'];
3201         // error if no id or parenturi specified (for clients posting parent-uri as well)
3202         if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3203                 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3204                 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3205         }
3206
3207         // BadRequestException if no id specified (for clients using Twitter API)
3208         if ($id == 0) {
3209                 throw new BadRequestException('Message id not specified');
3210         }
3211
3212         // add parent-uri to sql command if specified by calling app
3213         $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3214
3215         // error message if specified id is not in database
3216         if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
3217                 if ($verbose == "true") {
3218                         $answer = ['result' => 'error', 'message' => 'message id not in database'];
3219                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3220                 }
3221                 /// @todo BadRequestException ok for Twitter API clients?
3222                 throw new BadRequestException('message id not in database');
3223         }
3224
3225         // delete message
3226         $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
3227
3228         if ($verbose == "true") {
3229                 if ($result) {
3230                         // return success
3231                         $answer = ['result' => 'ok', 'message' => 'message deleted'];
3232                         return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
3233                 } else {
3234                         $answer = ['result' => 'error', 'message' => 'unknown error'];
3235                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3236                 }
3237         }
3238         /// @todo return JSON data like Twitter API not yet implemented
3239 }
3240
3241 /// @TODO move to top of file or somewhere better
3242 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3243
3244 /**
3245  * Unfollow Contact
3246  *
3247  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3248  * @return string|array
3249  * @throws HTTPException\BadRequestException
3250  * @throws HTTPException\ExpectationFailedException
3251  * @throws HTTPException\ForbiddenException
3252  * @throws HTTPException\InternalServerErrorException
3253  * @throws HTTPException\NotFoundException
3254  * @see   https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3255  */
3256 function api_friendships_destroy($type)
3257 {
3258         $uid = api_user();
3259
3260         if ($uid === false) {
3261                 throw new HTTPException\ForbiddenException();
3262         }
3263
3264         $owner = User::getOwnerDataById($uid);
3265         if (!$owner) {
3266                 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3267                 throw new HTTPException\NotFoundException('Error Processing Request');
3268         }
3269
3270         $contact_id = $_REQUEST['user_id'] ?? 0;
3271
3272         if (empty($contact_id)) {
3273                 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3274                 throw new HTTPException\BadRequestException('no user_id specified');
3275         }
3276
3277         // Get Contact by given id
3278         $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3279
3280         if(!DBA::isResult($contact)) {
3281                 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3282                 throw new HTTPException\NotFoundException('no contact found to given ID');
3283         }
3284
3285         $url = $contact['url'];
3286
3287         $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3288                         $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3289                         Strings::normaliseLink($url), $url];
3290         $contact = DBA::selectFirst('contact', [], $condition);
3291
3292         if (!DBA::isResult($contact)) {
3293                 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3294                 throw new HTTPException\NotFoundException('Not following Contact');
3295         }
3296
3297         try {
3298                 $result = Contact::terminateFriendship($owner, $contact);
3299
3300                 if ($result === null) {
3301                         Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3302                         throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3303                 }
3304
3305                 if ($result === false) {
3306                         throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3307                 }
3308         } catch (Exception $e) {
3309                 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3310                 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3311         }
3312
3313         // "uid" and "self" are only needed for some internal stuff, so remove it from here
3314         unset($contact['uid']);
3315         unset($contact['self']);
3316
3317         // Set screen_name since Twidere requests it
3318         $contact['screen_name'] = $contact['nick'];
3319
3320         return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
3321 }
3322
3323 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3324
3325 /**
3326  *
3327  * @param string $type Return type (atom, rss, xml, json)
3328  * @param string $box
3329  * @param string $verbose
3330  *
3331  * @return array|string
3332  * @throws BadRequestException
3333  * @throws ForbiddenException
3334  * @throws ImagickException
3335  * @throws InternalServerErrorException
3336  * @throws UnauthorizedException
3337  */
3338 function api_direct_messages_box($type, $box, $verbose)
3339 {
3340         $a = DI::app();
3341         if (api_user() === false) {
3342                 throw new ForbiddenException();
3343         }
3344         // params
3345         $count = $_GET['count'] ?? 20;
3346         $page = $_REQUEST['page'] ?? 1;
3347
3348         $since_id = $_REQUEST['since_id'] ?? 0;
3349         $max_id = $_REQUEST['max_id'] ?? 0;
3350
3351         $user_id = $_REQUEST['user_id'] ?? '';
3352         $screen_name = $_REQUEST['screen_name'] ?? '';
3353
3354         //  caller user info
3355         unset($_REQUEST["user_id"]);
3356         unset($_GET["user_id"]);
3357
3358         unset($_REQUEST["screen_name"]);
3359         unset($_GET["screen_name"]);
3360
3361         $user_info = api_get_user();
3362         if ($user_info === false) {
3363                 throw new ForbiddenException();
3364         }
3365         $profile_url = $user_info["url"];
3366
3367         // pagination
3368         $start = max(0, ($page - 1) * $count);
3369
3370         $sql_extra = "";
3371
3372         // filters
3373         if ($box=="sentbox") {
3374                 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3375         } elseif ($box == "conversation") {
3376                 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '')  . "'";
3377         } elseif ($box == "all") {
3378                 $sql_extra = "true";
3379         } elseif ($box == "inbox") {
3380                 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3381         }
3382
3383         if ($max_id > 0) {
3384                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3385         }
3386
3387         if ($user_id != "") {
3388                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3389         } elseif ($screen_name !="") {
3390                 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3391         }
3392
3393         $r = DBA::toArray(DBA::p(
3394                 "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 ?,?",
3395                 api_user(),
3396                 $since_id,
3397                 $start,
3398                 $count
3399         ));
3400         if ($verbose == "true" && !DBA::isResult($r)) {
3401                 $answer = ['result' => 'error', 'message' => 'no mails available'];
3402                 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
3403         }
3404
3405         $ret = [];
3406         foreach ($r as $item) {
3407                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3408                         $recipient = $user_info;
3409                         $sender = api_get_user(Strings::normaliseLink($item['contact-url']));
3410                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3411                         $recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
3412                         $sender = $user_info;
3413                 }
3414
3415                 if (isset($recipient) && isset($sender)) {
3416                         $ret[] = api_format_messages($item, $recipient, $sender);
3417                 }
3418         }
3419
3420
3421         $data = ['direct_message' => $ret];
3422         switch ($type) {
3423                 case "atom":
3424                         break;
3425                 case "rss":
3426                         $data = api_rss_extra($a, $data, $user_info);
3427                         break;
3428         }
3429
3430         return DI::apiResponse()->formatData("direct-messages", $type, $data);
3431 }
3432
3433 /**
3434  * Returns the most recent direct messages sent by the user.
3435  *
3436  * @param string $type Return type (atom, rss, xml, json)
3437  *
3438  * @return array|string
3439  * @throws BadRequestException
3440  * @throws ForbiddenException
3441  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3442  */
3443 function api_direct_messages_sentbox($type)
3444 {
3445         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3446         return api_direct_messages_box($type, "sentbox", $verbose);
3447 }
3448
3449 /**
3450  * Returns the most recent direct messages sent to the user.
3451  *
3452  * @param string $type Return type (atom, rss, xml, json)
3453  *
3454  * @return array|string
3455  * @throws BadRequestException
3456  * @throws ForbiddenException
3457  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3458  */
3459 function api_direct_messages_inbox($type)
3460 {
3461         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3462         return api_direct_messages_box($type, "inbox", $verbose);
3463 }
3464
3465 /**
3466  *
3467  * @param string $type Return type (atom, rss, xml, json)
3468  *
3469  * @return array|string
3470  * @throws BadRequestException
3471  * @throws ForbiddenException
3472  */
3473 function api_direct_messages_all($type)
3474 {
3475         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3476         return api_direct_messages_box($type, "all", $verbose);
3477 }
3478
3479 /**
3480  *
3481  * @param string $type Return type (atom, rss, xml, json)
3482  *
3483  * @return array|string
3484  * @throws BadRequestException
3485  * @throws ForbiddenException
3486  */
3487 function api_direct_messages_conversation($type)
3488 {
3489         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3490         return api_direct_messages_box($type, "conversation", $verbose);
3491 }
3492
3493 /// @TODO move to top of file or somewhere better
3494 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3495 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3496 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3497 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3498
3499 /**
3500  * list all photos of the authenticated user
3501  *
3502  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3503  * @return string|array
3504  * @throws ForbiddenException
3505  * @throws InternalServerErrorException
3506  */
3507 function api_fr_photos_list($type)
3508 {
3509         if (api_user() === false) {
3510                 throw new ForbiddenException();
3511         }
3512         $r = DBA::toArray(DBA::p(
3513                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3514                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3515                 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
3516                 local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
3517         ));
3518         $typetoext = [
3519                 'image/jpeg' => 'jpg',
3520                 'image/png' => 'png',
3521                 'image/gif' => 'gif'
3522         ];
3523         $data = ['photo'=>[]];
3524         if (DBA::isResult($r)) {
3525                 foreach ($r as $rr) {
3526                         $photo = [];
3527                         $photo['id'] = $rr['resource-id'];
3528                         $photo['album'] = $rr['album'];
3529                         $photo['filename'] = $rr['filename'];
3530                         $photo['type'] = $rr['type'];
3531                         $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3532                         $photo['created'] = $rr['created'];
3533                         $photo['edited'] = $rr['edited'];
3534                         $photo['desc'] = $rr['desc'];
3535
3536                         if ($type == "xml") {
3537                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3538                         } else {
3539                                 $photo['thumb'] = $thumb;
3540                                 $data['photo'][] = $photo;
3541                         }
3542                 }
3543         }
3544         return DI::apiResponse()->formatData("photos", $type, $data);
3545 }
3546
3547 /**
3548  * upload a new photo or change an existing photo
3549  *
3550  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3551  * @return string|array
3552  * @throws BadRequestException
3553  * @throws ForbiddenException
3554  * @throws ImagickException
3555  * @throws InternalServerErrorException
3556  * @throws NotFoundException
3557  */
3558 function api_fr_photo_create_update($type)
3559 {
3560         if (api_user() === false) {
3561                 throw new ForbiddenException();
3562         }
3563         // input params
3564         $photo_id  = $_REQUEST['photo_id']  ?? null;
3565         $desc      = $_REQUEST['desc']      ?? null;
3566         $album     = $_REQUEST['album']     ?? null;
3567         $album_new = $_REQUEST['album_new'] ?? null;
3568         $allow_cid = $_REQUEST['allow_cid'] ?? null;
3569         $deny_cid  = $_REQUEST['deny_cid' ] ?? null;
3570         $allow_gid = $_REQUEST['allow_gid'] ?? null;
3571         $deny_gid  = $_REQUEST['deny_gid' ] ?? null;
3572         $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3573
3574         // do several checks on input parameters
3575         // we do not allow calls without album string
3576         if ($album == null) {
3577                 throw new BadRequestException("no albumname specified");
3578         }
3579         // if photo_id == null --> we are uploading a new photo
3580         if ($photo_id == null) {
3581                 $mode = "create";
3582
3583                 // error if no media posted in create-mode
3584                 if (empty($_FILES['media'])) {
3585                         // Output error
3586                         throw new BadRequestException("no media data submitted");
3587                 }
3588
3589                 // album_new will be ignored in create-mode
3590                 $album_new = "";
3591         } else {
3592                 $mode = "update";
3593
3594                 // check if photo is existing in databasei
3595                 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
3596                         throw new BadRequestException("photo not available");
3597                 }
3598         }
3599
3600         // checks on acl strings provided by clients
3601         $acl_input_error = false;
3602         $acl_input_error |= check_acl_input($allow_cid);
3603         $acl_input_error |= check_acl_input($deny_cid);
3604         $acl_input_error |= check_acl_input($allow_gid);
3605         $acl_input_error |= check_acl_input($deny_gid);
3606         if ($acl_input_error) {
3607                 throw new BadRequestException("acl data invalid");
3608         }
3609         // now let's upload the new media in create-mode
3610         if ($mode == "create") {
3611                 $media = $_FILES['media'];
3612                 $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);
3613
3614                 // return success of updating or error message
3615                 if (!is_null($data)) {
3616                         return DI::apiResponse()->formatData("photo_create", $type, $data);
3617                 } else {
3618                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3619                 }
3620         }
3621
3622         // now let's do the changes in update-mode
3623         if ($mode == "update") {
3624                 $updated_fields = [];
3625
3626                 if (!is_null($desc)) {
3627                         $updated_fields['desc'] = $desc;
3628                 }
3629
3630                 if (!is_null($album_new)) {
3631                         $updated_fields['album'] = $album_new;
3632                 }
3633
3634                 if (!is_null($allow_cid)) {
3635                         $allow_cid = trim($allow_cid);
3636                         $updated_fields['allow_cid'] = $allow_cid;
3637                 }
3638
3639                 if (!is_null($deny_cid)) {
3640                         $deny_cid = trim($deny_cid);
3641                         $updated_fields['deny_cid'] = $deny_cid;
3642                 }
3643
3644                 if (!is_null($allow_gid)) {
3645                         $allow_gid = trim($allow_gid);
3646                         $updated_fields['allow_gid'] = $allow_gid;
3647                 }
3648
3649                 if (!is_null($deny_gid)) {
3650                         $deny_gid = trim($deny_gid);
3651                         $updated_fields['deny_gid'] = $deny_gid;
3652                 }
3653
3654                 $result = false;
3655                 if (count($updated_fields) > 0) {
3656                         $nothingtodo = false;
3657                         $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
3658                 } else {
3659                         $nothingtodo = true;
3660                 }
3661
3662                 if (!empty($_FILES['media'])) {
3663                         $nothingtodo = false;
3664                         $media = $_FILES['media'];
3665                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
3666                         if (!is_null($data)) {
3667                                 return DI::apiResponse()->formatData("photo_update", $type, $data);
3668                         }
3669                 }
3670
3671                 // return success of updating or error message
3672                 if ($result) {
3673                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3674                         return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3675                 } else {
3676                         if ($nothingtodo) {
3677                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3678                                 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3679                         }
3680                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3681                 }
3682         }
3683         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3684 }
3685
3686 /**
3687  * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3688  *
3689  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3690  * @return string|array
3691  * @throws BadRequestException
3692  * @throws ForbiddenException
3693  * @throws InternalServerErrorException
3694  * @throws NotFoundException
3695  */
3696 function api_fr_photo_detail($type)
3697 {
3698         if (api_user() === false) {
3699                 throw new ForbiddenException();
3700         }
3701         if (empty($_REQUEST['photo_id'])) {
3702                 throw new BadRequestException("No photo id.");
3703         }
3704
3705         $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3706         $photo_id = $_REQUEST['photo_id'];
3707
3708         // prepare json/xml output with data from database for the requested photo
3709         $data = prepare_photo_data($type, $scale, $photo_id);
3710
3711         return DI::apiResponse()->formatData("photo_detail", $type, $data);
3712 }
3713
3714
3715 /**
3716  * updates the profile image for the user (either a specified profile or the default profile)
3717  *
3718  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3719  *
3720  * @return string|array
3721  * @throws BadRequestException
3722  * @throws ForbiddenException
3723  * @throws ImagickException
3724  * @throws InternalServerErrorException
3725  * @throws NotFoundException
3726  * @see   https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3727  */
3728 function api_account_update_profile_image($type)
3729 {
3730         if (api_user() === false) {
3731                 throw new ForbiddenException();
3732         }
3733         // input params
3734         $profile_id = $_REQUEST['profile_id'] ?? 0;
3735
3736         // error if image data is missing
3737         if (empty($_FILES['image'])) {
3738                 throw new BadRequestException("no media data submitted");
3739         }
3740
3741         // check if specified profile id is valid
3742         if ($profile_id != 0) {
3743                 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
3744                 // error message if specified profile id is not in database
3745                 if (!DBA::isResult($profile)) {
3746                         throw new BadRequestException("profile_id not available");
3747                 }
3748                 $is_default_profile = $profile['is-default'];
3749         } else {
3750                 $is_default_profile = 1;
3751         }
3752
3753         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3754         $media = null;
3755         if (!empty($_FILES['image'])) {
3756                 $media = $_FILES['image'];
3757         } elseif (!empty($_FILES['media'])) {
3758                 $media = $_FILES['media'];
3759         }
3760         // save new profile image
3761         $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
3762
3763         // get filetype
3764         if (is_array($media['type'])) {
3765                 $filetype = $media['type'][0];
3766         } else {
3767                 $filetype = $media['type'];
3768         }
3769         if ($filetype == "image/jpeg") {
3770                 $fileext = "jpg";
3771         } elseif ($filetype == "image/png") {
3772                 $fileext = "png";
3773         } else {
3774                 throw new InternalServerErrorException('Unsupported filetype');
3775         }
3776
3777         // change specified profile or all profiles to the new resource-id
3778         if ($is_default_profile) {
3779                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
3780                 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3781         } else {
3782                 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3783                         'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3784                 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
3785         }
3786
3787         Contact::updateSelfFromUserID(api_user(), true);
3788
3789         // Update global directory in background
3790         Profile::publishUpdate(api_user());
3791
3792         // output for client
3793         if ($data) {
3794                 return api_account_verify_credentials($type);
3795         } else {
3796                 // SaveMediaToDatabase failed for some reason
3797                 throw new InternalServerErrorException("image upload failed");
3798         }
3799 }
3800
3801 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3802 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3803 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3804 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3805 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3806 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3807
3808 /**
3809  * Update user profile
3810  *
3811  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3812  *
3813  * @return array|string
3814  * @throws BadRequestException
3815  * @throws ForbiddenException
3816  * @throws ImagickException
3817  * @throws InternalServerErrorException
3818  * @throws UnauthorizedException
3819  */
3820 function api_account_update_profile($type)
3821 {
3822         $local_user = api_user();
3823         $api_user = api_get_user();
3824
3825         if (!empty($_POST['name'])) {
3826                 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
3827                 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
3828                 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
3829                 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3830         }
3831
3832         if (isset($_POST['description'])) {
3833                 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
3834                 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
3835                 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3836         }
3837
3838         Profile::publishUpdate($local_user);
3839
3840         return api_account_verify_credentials($type);
3841 }
3842
3843 /// @TODO move to top of file or somewhere better
3844 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3845
3846 /**
3847  *
3848  * @param string $acl_string
3849  * @return bool
3850  * @throws Exception
3851  */
3852 function check_acl_input($acl_string)
3853 {
3854         if (empty($acl_string)) {
3855                 return false;
3856         }
3857
3858         $contact_not_found = false;
3859
3860         // split <x><y><z> into array of cid's
3861         preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3862
3863         // check for each cid if it is available on server
3864         $cid_array = $array[0];
3865         foreach ($cid_array as $cid) {
3866                 $cid = str_replace("<", "", $cid);
3867                 $cid = str_replace(">", "", $cid);
3868                 $condition = ['id' => $cid, 'uid' => api_user()];
3869                 $contact_not_found |= !DBA::exists('contact', $condition);
3870         }
3871         return $contact_not_found;
3872 }
3873
3874 /**
3875  * @param string  $mediatype
3876  * @param array   $media
3877  * @param string  $type
3878  * @param string  $album
3879  * @param string  $allow_cid
3880  * @param string  $deny_cid
3881  * @param string  $allow_gid
3882  * @param string  $deny_gid
3883  * @param string  $desc
3884  * @param integer $phototype
3885  * @param boolean $visibility
3886  * @param string  $photo_id
3887  * @return array
3888  * @throws BadRequestException
3889  * @throws ForbiddenException
3890  * @throws ImagickException
3891  * @throws InternalServerErrorException
3892  * @throws NotFoundException
3893  * @throws UnauthorizedException
3894  */
3895 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype = 0, $visibility = false, $photo_id = null)
3896 {
3897         $visitor   = 0;
3898         $src = "";
3899         $filetype = "";
3900         $filename = "";
3901         $filesize = 0;
3902
3903         if (is_array($media)) {
3904                 if (is_array($media['tmp_name'])) {
3905                         $src = $media['tmp_name'][0];
3906                 } else {
3907                         $src = $media['tmp_name'];
3908                 }
3909                 if (is_array($media['name'])) {
3910                         $filename = basename($media['name'][0]);
3911                 } else {
3912                         $filename = basename($media['name']);
3913                 }
3914                 if (is_array($media['size'])) {
3915                         $filesize = intval($media['size'][0]);
3916                 } else {
3917                         $filesize = intval($media['size']);
3918                 }
3919                 if (is_array($media['type'])) {
3920                         $filetype = $media['type'][0];
3921                 } else {
3922                         $filetype = $media['type'];
3923                 }
3924         }
3925
3926         $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
3927
3928         logger::info(
3929                 "File upload src: " . $src . " - filename: " . $filename .
3930                 " - size: " . $filesize . " - type: " . $filetype);
3931
3932         // check if there was a php upload error
3933         if ($filesize == 0 && $media['error'] == 1) {
3934                 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3935         }
3936         // check against max upload size within Friendica instance
3937         $maximagesize = DI::config()->get('system', 'maximagesize');
3938         if ($maximagesize && ($filesize > $maximagesize)) {
3939                 $formattedBytes = Strings::formatBytes($maximagesize);
3940                 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3941         }
3942
3943         // create Photo instance with the data of the image
3944         $imagedata = @file_get_contents($src);
3945         $Image = new Image($imagedata, $filetype);
3946         if (!$Image->isValid()) {
3947                 throw new InternalServerErrorException("unable to process image data");
3948         }
3949
3950         // check orientation of image
3951         $Image->orient($src);
3952         @unlink($src);
3953
3954         // check max length of images on server
3955         $max_length = DI::config()->get('system', 'max_image_length');
3956         if ($max_length > 0) {
3957                 $Image->scaleDown($max_length);
3958                 logger::info("File upload: Scaling picture to new size " . $max_length);
3959         }
3960         $width = $Image->getWidth();
3961         $height = $Image->getHeight();
3962
3963         // create a new resource-id if not already provided
3964         $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
3965
3966         if ($mediatype == "photo") {
3967                 // upload normal image (scales 0, 1, 2)
3968                 logger::info("photo upload: starting new photo upload");
3969
3970                 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3971                 if (!$r) {
3972                         logger::notice("photo upload: image upload with scale 0 (original size) failed");
3973                 }
3974                 if ($width > 640 || $height > 640) {
3975                         $Image->scaleDown(640);
3976                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3977                         if (!$r) {
3978                                 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
3979                         }
3980                 }
3981
3982                 if ($width > 320 || $height > 320) {
3983                         $Image->scaleDown(320);
3984                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3985                         if (!$r) {
3986                                 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
3987                         }
3988                 }
3989                 logger::info("photo upload: new photo upload ended");
3990         } elseif ($mediatype == "profileimage") {
3991                 // upload profile image (scales 4, 5, 6)
3992                 logger::info("photo upload: starting new profile image upload");
3993
3994                 if ($width > 300 || $height > 300) {
3995                         $Image->scaleDown(300);
3996                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3997                         if (!$r) {
3998                                 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
3999                         }
4000                 }
4001
4002                 if ($width > 80 || $height > 80) {
4003                         $Image->scaleDown(80);
4004                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4005                         if (!$r) {
4006                                 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
4007                         }
4008                 }
4009
4010                 if ($width > 48 || $height > 48) {
4011                         $Image->scaleDown(48);
4012                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4013                         if (!$r) {
4014                                 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
4015                         }
4016                 }
4017                 $Image->__destruct();
4018                 logger::info("photo upload: new profile image upload ended");
4019         }
4020
4021         if (!empty($r)) {
4022                 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4023                 if ($photo_id == null && $mediatype == "photo") {
4024                         post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4025                 }
4026                 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4027                 return prepare_photo_data($type, false, $resource_id);
4028         } else {
4029                 throw new InternalServerErrorException("image upload failed");
4030         }
4031 }
4032
4033 /**
4034  *
4035  * @param string  $hash
4036  * @param string  $allow_cid
4037  * @param string  $deny_cid
4038  * @param string  $allow_gid
4039  * @param string  $deny_gid
4040  * @param string  $filetype
4041  * @param boolean $visibility
4042  * @throws InternalServerErrorException
4043  */
4044 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4045 {
4046         // get data about the api authenticated user
4047         $uri = Item::newURI(intval(api_user()));
4048         $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4049
4050         $arr = [];
4051         $arr['guid']          = System::createUUID();
4052         $arr['uid']           = intval(api_user());
4053         $arr['uri']           = $uri;
4054         $arr['type']          = 'photo';
4055         $arr['wall']          = 1;
4056         $arr['resource-id']   = $hash;
4057         $arr['contact-id']    = $owner_record['id'];
4058         $arr['owner-name']    = $owner_record['name'];
4059         $arr['owner-link']    = $owner_record['url'];
4060         $arr['owner-avatar']  = $owner_record['thumb'];
4061         $arr['author-name']   = $owner_record['name'];
4062         $arr['author-link']   = $owner_record['url'];
4063         $arr['author-avatar'] = $owner_record['thumb'];
4064         $arr['title']         = "";
4065         $arr['allow_cid']     = $allow_cid;
4066         $arr['allow_gid']     = $allow_gid;
4067         $arr['deny_cid']      = $deny_cid;
4068         $arr['deny_gid']      = $deny_gid;
4069         $arr['visible']       = $visibility;
4070         $arr['origin']        = 1;
4071
4072         $typetoext = [
4073                         'image/jpeg' => 'jpg',
4074                         'image/png' => 'png',
4075                         'image/gif' => 'gif'
4076                         ];
4077
4078         // adds link to the thumbnail scale photo
4079         $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4080                                 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4081                                 . '[/url]';
4082
4083         // do the magic for storing the item in the database and trigger the federation to other contacts
4084         Item::insert($arr);
4085 }
4086
4087 /**
4088  *
4089  * @param string $type
4090  * @param int    $scale
4091  * @param string $photo_id
4092  *
4093  * @return array
4094  * @throws BadRequestException
4095  * @throws ForbiddenException
4096  * @throws ImagickException
4097  * @throws InternalServerErrorException
4098  * @throws NotFoundException
4099  * @throws UnauthorizedException
4100  */
4101 function prepare_photo_data($type, $scale, $photo_id)
4102 {
4103         $a = DI::app();
4104         $user_info = api_get_user();
4105
4106         if ($user_info === false) {
4107                 throw new ForbiddenException();
4108         }
4109
4110         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4111         $data_sql = ($scale === false ? "" : "data, ");
4112
4113         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4114         // clients needs to convert this in their way for further processing
4115         $r = DBA::toArray(DBA::p(
4116                 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4117                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4118                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4119                         FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
4120                                    `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4121                                    `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4122                 local_user(),
4123                 $photo_id
4124         ));
4125
4126         $typetoext = [
4127                 'image/jpeg' => 'jpg',
4128                 'image/png' => 'png',
4129                 'image/gif' => 'gif'
4130         ];
4131
4132         // prepare output data for photo
4133         if (DBA::isResult($r)) {
4134                 $data = ['photo' => $r[0]];
4135                 $data['photo']['id'] = $data['photo']['resource-id'];
4136                 if ($scale !== false) {
4137                         $data['photo']['data'] = base64_encode($data['photo']['data']);
4138                 } else {
4139                         unset($data['photo']['datasize']); //needed only with scale param
4140                 }
4141                 if ($type == "xml") {
4142                         $data['photo']['links'] = [];
4143                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4144                                 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4145                                                                                 "scale" => $k,
4146                                                                                 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4147                         }
4148                 } else {
4149                         $data['photo']['link'] = [];
4150                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4151                         $i = 0;
4152                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4153                                 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4154                                 $i++;
4155                         }
4156                 }
4157                 unset($data['photo']['resource-id']);
4158                 unset($data['photo']['minscale']);
4159                 unset($data['photo']['maxscale']);
4160         } else {
4161                 throw new NotFoundException();
4162         }
4163
4164         // retrieve item element for getting activities (like, dislike etc.) related to photo
4165         $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4166         $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4167         if (!DBA::isResult($item)) {
4168                 throw new NotFoundException('Photo-related item not found.');
4169         }
4170
4171         $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4172
4173         // retrieve comments on photo
4174         $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4175                 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4176
4177         $statuses = Post::selectForUser(api_user(), [], $condition);
4178
4179         // prepare output of comments
4180         $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4181         $comments = [];
4182         if ($type == "xml") {
4183                 $k = 0;
4184                 foreach ($commentData as $comment) {
4185                         $comments[$k++ . ":comment"] = $comment;
4186                 }
4187         } else {
4188                 foreach ($commentData as $comment) {
4189                         $comments[] = $comment;
4190                 }
4191         }
4192         $data['photo']['friendica_comments'] = $comments;
4193
4194         // include info if rights on photo and rights on item are mismatching
4195         $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4196                 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4197                 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4198                 $data['photo']['deny_gid'] != $item['deny_gid'];
4199         $data['photo']['rights_mismatch'] = $rights_mismatch;
4200
4201         return $data;
4202 }
4203
4204 /**
4205  * Return an item with announcer data if it had been announced
4206  *
4207  * @param array $item Item array
4208  * @return array Item array with announce data
4209  */
4210 function api_get_announce($item)
4211 {
4212         // Quit if the item already has got a different owner and author
4213         if ($item['owner-id'] != $item['author-id']) {
4214                 return [];
4215         }
4216
4217         // Don't change original or Diaspora posts
4218         if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4219                 return [];
4220         }
4221
4222         // Quit if we do now the original author and it had been a post from a native network
4223         if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4224                 return [];
4225         }
4226
4227         $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4228         $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4229         $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4230         if (!DBA::isResult($announce)) {
4231                 return [];
4232         }
4233
4234         return array_merge($item, $announce);
4235 }
4236
4237 /**
4238  *
4239  * @param array $item
4240  *
4241  * @return array
4242  * @throws Exception
4243  */
4244 function api_in_reply_to($item)
4245 {
4246         $in_reply_to = [];
4247
4248         $in_reply_to['status_id'] = null;
4249         $in_reply_to['user_id'] = null;
4250         $in_reply_to['status_id_str'] = null;
4251         $in_reply_to['user_id_str'] = null;
4252         $in_reply_to['screen_name'] = null;
4253
4254         if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4255                 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4256                 if (DBA::isResult($parent)) {
4257                         $in_reply_to['status_id'] = intval($parent['id']);
4258                 } else {
4259                         $in_reply_to['status_id'] = intval($item['parent']);
4260                 }
4261
4262                 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4263
4264                 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4265                 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4266
4267                 if (DBA::isResult($parent)) {
4268                         $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4269                         $in_reply_to['user_id'] = intval($parent['author-id']);
4270                         $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4271                 }
4272
4273                 // There seems to be situation, where both fields are identical:
4274                 // https://github.com/friendica/friendica/issues/1010
4275                 // This is a bugfix for that.
4276                 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4277                         Logger::warning(API_LOG_PREFIX . 'ID {id} is similar to reply-to {reply-to}', ['module' => 'api', 'action' => 'in_reply_to', 'id' => $item['id'], 'reply-to' => $in_reply_to['status_id']]);
4278                         $in_reply_to['status_id'] = null;
4279                         $in_reply_to['user_id'] = null;
4280                         $in_reply_to['status_id_str'] = null;
4281                         $in_reply_to['user_id_str'] = null;
4282                         $in_reply_to['screen_name'] = null;
4283                 }
4284         }
4285
4286         return $in_reply_to;
4287 }
4288
4289 /**
4290  *
4291  * @param string $text
4292  *
4293  * @return string
4294  * @throws InternalServerErrorException
4295  */
4296 function api_clean_plain_items($text)
4297 {
4298         $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4299
4300         $text = BBCode::cleanPictureLinks($text);
4301         $URLSearchString = "^\[\]";
4302
4303         $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4304
4305         if ($include_entities == "true") {
4306                 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4307         }
4308
4309         // Simplify "attachment" element
4310         $text = BBCode::removeAttachment($text);
4311
4312         return $text;
4313 }
4314
4315 /**
4316  *
4317  * @param array $contacts
4318  *
4319  * @return void
4320  */
4321 function api_best_nickname(&$contacts)
4322 {
4323         $best_contact = [];
4324
4325         if (count($contacts) == 0) {
4326                 return;
4327         }
4328
4329         foreach ($contacts as $contact) {
4330                 if ($contact["network"] == "") {
4331                         $contact["network"] = "dfrn";
4332                         $best_contact = [$contact];
4333                 }
4334         }
4335
4336         if (sizeof($best_contact) == 0) {
4337                 foreach ($contacts as $contact) {
4338                         if ($contact["network"] == "dfrn") {
4339                                 $best_contact = [$contact];
4340                         }
4341                 }
4342         }
4343
4344         if (sizeof($best_contact) == 0) {
4345                 foreach ($contacts as $contact) {
4346                         if ($contact["network"] == "dspr") {
4347                                 $best_contact = [$contact];
4348                         }
4349                 }
4350         }
4351
4352         if (sizeof($best_contact) == 0) {
4353                 foreach ($contacts as $contact) {
4354                         if ($contact["network"] == "stat") {
4355                                 $best_contact = [$contact];
4356                         }
4357                 }
4358         }
4359
4360         if (sizeof($best_contact) == 0) {
4361                 foreach ($contacts as $contact) {
4362                         if ($contact["network"] == "pump") {
4363                                 $best_contact = [$contact];
4364                         }
4365                 }
4366         }
4367
4368         if (sizeof($best_contact) == 0) {
4369                 foreach ($contacts as $contact) {
4370                         if ($contact["network"] == "twit") {
4371                                 $best_contact = [$contact];
4372                         }
4373                 }
4374         }
4375
4376         if (sizeof($best_contact) == 1) {
4377                 $contacts = $best_contact;
4378         } else {
4379                 $contacts = [$contacts[0]];
4380         }
4381 }
4382
4383 /**
4384  * Return all or a specified group of the user with the containing contacts.
4385  *
4386  * @param string $type Return type (atom, rss, xml, json)
4387  *
4388  * @return array|string
4389  * @throws BadRequestException
4390  * @throws ForbiddenException
4391  * @throws ImagickException
4392  * @throws InternalServerErrorException
4393  * @throws UnauthorizedException
4394  */
4395 function api_friendica_group_show($type)
4396 {
4397         $a = DI::app();
4398
4399         if (api_user() === false) {
4400                 throw new ForbiddenException();
4401         }
4402
4403         // params
4404         $user_info = api_get_user();
4405         $gid = $_REQUEST['gid'] ?? 0;
4406         $uid = $user_info['uid'];
4407
4408         // get data of the specified group id or all groups if not specified
4409         if ($gid != 0) {
4410                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
4411
4412                 // error message if specified gid is not in database
4413                 if (!DBA::isResult($groups)) {
4414                         throw new BadRequestException("gid not available");
4415                 }
4416         } else {
4417                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
4418         }
4419
4420         // loop through all groups and retrieve all members for adding data in the user array
4421         $grps = [];
4422         foreach ($groups as $rr) {
4423                 $members = Contact\Group::getById($rr['id']);
4424                 $users = [];
4425
4426                 if ($type == "xml") {
4427                         $user_element = "users";
4428                         $k = 0;
4429                         foreach ($members as $member) {
4430                                 $user = api_get_user($member['nurl']);
4431                                 $users[$k++.":user"] = $user;
4432                         }
4433                 } else {
4434                         $user_element = "user";
4435                         foreach ($members as $member) {
4436                                 $user = api_get_user($member['nurl']);
4437                                 $users[] = $user;
4438                         }
4439                 }
4440                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
4441         }
4442         return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
4443 }
4444
4445 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4446
4447 /**
4448  * Delete a group.
4449  *
4450  * @param string $type Return type (atom, rss, xml, json)
4451  *
4452  * @return array|string
4453  * @throws BadRequestException
4454  * @throws ForbiddenException
4455  * @throws ImagickException
4456  * @throws InternalServerErrorException
4457  * @throws UnauthorizedException
4458  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
4459  */
4460 function api_lists_destroy($type)
4461 {
4462         $a = DI::app();
4463
4464         if (api_user() === false) {
4465                 throw new ForbiddenException();
4466         }
4467
4468         // params
4469         $user_info = api_get_user();
4470         $gid = $_REQUEST['list_id'] ?? 0;
4471         $uid = $user_info['uid'];
4472
4473         // error if no gid specified
4474         if ($gid == 0) {
4475                 throw new BadRequestException('gid not specified');
4476         }
4477
4478         // get data of the specified group id
4479         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4480         // error message if specified gid is not in database
4481         if (!$group) {
4482                 throw new BadRequestException('gid not available');
4483         }
4484
4485         if (Group::remove($gid)) {
4486                 $list = [
4487                         'name' => $group['name'],
4488                         'id' => intval($gid),
4489                         'id_str' => (string) $gid,
4490                         'user' => $user_info
4491                 ];
4492
4493                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4494         }
4495 }
4496
4497 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
4498
4499 /**
4500  * Add a new group to the database.
4501  *
4502  * @param  string $name  Group name
4503  * @param  int    $uid   User ID
4504  * @param  array  $users List of users to add to the group
4505  *
4506  * @return array
4507  * @throws BadRequestException
4508  */
4509 function group_create($name, $uid, $users = [])
4510 {
4511         // error if no name specified
4512         if ($name == "") {
4513                 throw new BadRequestException('group name not specified');
4514         }
4515
4516         // error message if specified group name already exists
4517         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
4518                 throw new BadRequestException('group name already exists');
4519         }
4520
4521         // Check if the group needs to be reactivated
4522         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
4523                 $reactivate_group = true;
4524         }
4525
4526         // create group
4527         $ret = Group::create($uid, $name);
4528         if ($ret) {
4529                 $gid = Group::getIdByName($uid, $name);
4530         } else {
4531                 throw new BadRequestException('other API error');
4532         }
4533
4534         // add members
4535         $erroraddinguser = false;
4536         $errorusers = [];
4537         foreach ($users as $user) {
4538                 $cid = $user['cid'];
4539                 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4540                         Group::addMember($gid, $cid);
4541                 } else {
4542                         $erroraddinguser = true;
4543                         $errorusers[] = $cid;
4544                 }
4545         }
4546
4547         // return success message incl. missing users in array
4548         $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
4549
4550         return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4551 }
4552
4553 /**
4554  * Create the specified group with the posted array of contacts.
4555  *
4556  * @param string $type Return type (atom, rss, xml, json)
4557  *
4558  * @return array|string
4559  * @throws BadRequestException
4560  * @throws ForbiddenException
4561  * @throws ImagickException
4562  * @throws InternalServerErrorException
4563  * @throws UnauthorizedException
4564  */
4565 function api_friendica_group_create($type)
4566 {
4567         $a = DI::app();
4568
4569         if (api_user() === false) {
4570                 throw new ForbiddenException();
4571         }
4572
4573         // params
4574         $user_info = api_get_user();
4575         $name = $_REQUEST['name'] ?? '';
4576         $uid = $user_info['uid'];
4577         $json = json_decode($_POST['json'], true);
4578         $users = $json['user'];
4579
4580         $success = group_create($name, $uid, $users);
4581
4582         return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
4583 }
4584
4585 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4586
4587 /**
4588  * Create a new group.
4589  *
4590  * @param string $type Return type (atom, rss, xml, json)
4591  *
4592  * @return array|string
4593  * @throws BadRequestException
4594  * @throws ForbiddenException
4595  * @throws ImagickException
4596  * @throws InternalServerErrorException
4597  * @throws UnauthorizedException
4598  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
4599  */
4600 function api_lists_create($type)
4601 {
4602         $a = DI::app();
4603
4604         if (api_user() === false) {
4605                 throw new ForbiddenException();
4606         }
4607
4608         // params
4609         $user_info = api_get_user();
4610         $name = $_REQUEST['name'] ?? '';
4611         $uid = $user_info['uid'];
4612
4613         $success = group_create($name, $uid);
4614         if ($success['success']) {
4615                 $grp = [
4616                         'name' => $success['name'],
4617                         'id' => intval($success['gid']),
4618                         'id_str' => (string) $success['gid'],
4619                         'user' => $user_info
4620                 ];
4621
4622                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
4623         }
4624 }
4625
4626 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4627
4628 /**
4629  * Update the specified group with the posted array of contacts.
4630  *
4631  * @param string $type Return type (atom, rss, xml, json)
4632  *
4633  * @return array|string
4634  * @throws BadRequestException
4635  * @throws ForbiddenException
4636  * @throws ImagickException
4637  * @throws InternalServerErrorException
4638  * @throws UnauthorizedException
4639  */
4640 function api_friendica_group_update($type)
4641 {
4642         $a = DI::app();
4643
4644         if (api_user() === false) {
4645                 throw new ForbiddenException();
4646         }
4647
4648         // params
4649         $user_info = api_get_user();
4650         $uid = $user_info['uid'];
4651         $gid = $_REQUEST['gid'] ?? 0;
4652         $name = $_REQUEST['name'] ?? '';
4653         $json = json_decode($_POST['json'], true);
4654         $users = $json['user'];
4655
4656         // error if no name specified
4657         if ($name == "") {
4658                 throw new BadRequestException('group name not specified');
4659         }
4660
4661         // error if no gid specified
4662         if ($gid == "") {
4663                 throw new BadRequestException('gid not specified');
4664         }
4665
4666         // remove members
4667         $members = Contact\Group::getById($gid);
4668         foreach ($members as $member) {
4669                 $cid = $member['id'];
4670                 foreach ($users as $user) {
4671                         $found = ($user['cid'] == $cid ? true : false);
4672                 }
4673                 if (!isset($found) || !$found) {
4674                         $gid = Group::getIdByName($uid, $name);
4675                         Group::removeMember($gid, $cid);
4676                 }
4677         }
4678
4679         // add members
4680         $erroraddinguser = false;
4681         $errorusers = [];
4682         foreach ($users as $user) {
4683                 $cid = $user['cid'];
4684
4685                 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4686                         Group::addMember($gid, $cid);
4687                 } else {
4688                         $erroraddinguser = true;
4689                         $errorusers[] = $cid;
4690                 }
4691         }
4692
4693         // return success message incl. missing users in array
4694         $status = ($erroraddinguser ? "missing user" : "ok");
4695         $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4696         return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
4697 }
4698
4699 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4700
4701 /**
4702  * Update information about a group.
4703  *
4704  * @param string $type Return type (atom, rss, xml, json)
4705  *
4706  * @return array|string
4707  * @throws BadRequestException
4708  * @throws ForbiddenException
4709  * @throws ImagickException
4710  * @throws InternalServerErrorException
4711  * @throws UnauthorizedException
4712  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4713  */
4714 function api_lists_update($type)
4715 {
4716         $a = DI::app();
4717
4718         if (api_user() === false) {
4719                 throw new ForbiddenException();
4720         }
4721
4722         // params
4723         $user_info = api_get_user();
4724         $gid = $_REQUEST['list_id'] ?? 0;
4725         $name = $_REQUEST['name'] ?? '';
4726         $uid = $user_info['uid'];
4727
4728         // error if no gid specified
4729         if ($gid == 0) {
4730                 throw new BadRequestException('gid not specified');
4731         }
4732
4733         // get data of the specified group id
4734         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4735         // error message if specified gid is not in database
4736         if (!$group) {
4737                 throw new BadRequestException('gid not available');
4738         }
4739
4740         if (Group::update($gid, $name)) {
4741                 $list = [
4742                         'name' => $name,
4743                         'id' => intval($gid),
4744                         'id_str' => (string) $gid,
4745                         'user' => $user_info
4746                 ];
4747
4748                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4749         }
4750 }
4751
4752 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4753
4754 /**
4755  * Set notification as seen and returns associated item (if possible)
4756  *
4757  * POST request with 'id' param as notification id
4758  *
4759  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4760  * @return string|array
4761  * @throws BadRequestException
4762  * @throws ForbiddenException
4763  * @throws ImagickException
4764  * @throws InternalServerErrorException
4765  * @throws UnauthorizedException
4766  */
4767 function api_friendica_notification_seen($type)
4768 {
4769         $a         = DI::app();
4770         $user_info = api_get_user();
4771
4772         if (api_user() === false || $user_info === false) {
4773                 throw new ForbiddenException();
4774         }
4775         if (DI::args()->getArgc() !== 4) {
4776                 throw new BadRequestException('Invalid argument count');
4777         }
4778
4779         $id = intval($_REQUEST['id'] ?? 0);
4780
4781         try {
4782                 $Notify = DI::notify()->selectOneById($id);
4783                 if ($Notify->uid !== api_user()) {
4784                         throw new NotFoundException();
4785                 }
4786
4787                 if ($Notify->uriId) {
4788                         DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
4789                 }
4790
4791                 $Notify->setSeen();
4792                 DI::notify()->save($Notify);
4793
4794                 if ($Notify->otype === Notification\ObjectType::ITEM) {
4795                         $item = Post::selectFirstForUser(api_user(), [], ['id' => $Notify->iid, 'uid' => api_user()]);
4796                         if (DBA::isResult($item)) {
4797                                 // we found the item, return it to the user
4798                                 $ret  = api_format_items([$item], $user_info, false, $type);
4799                                 $data = ['status' => $ret];
4800                                 return DI::apiResponse()->formatData('status', $type, $data);
4801                         }
4802                         // the item can't be found, but we set the notification as seen, so we count this as a success
4803                 }
4804
4805                 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
4806         } catch (NotFoundException $e) {
4807                 throw new BadRequestException('Invalid argument', $e);
4808         } catch (Exception $e) {
4809                 throw new InternalServerErrorException('Internal Server exception', $e);
4810         }
4811 }
4812
4813 /// @TODO move to top of file or somewhere better
4814 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4815
4816 /**
4817  * search for direct_messages containing a searchstring through api
4818  *
4819  * @param string $type      Known types are 'atom', 'rss', 'xml' and 'json'
4820  * @param string $box
4821  * @return string|array (success: success=true if found and search_result contains found messages,
4822  *                          success=false if nothing was found, search_result='nothing found',
4823  *                          error: result=error with error message)
4824  * @throws BadRequestException
4825  * @throws ForbiddenException
4826  * @throws ImagickException
4827  * @throws InternalServerErrorException
4828  * @throws UnauthorizedException
4829  */
4830 function api_friendica_direct_messages_search($type, $box = "")
4831 {
4832         $a = DI::app();
4833
4834         if (api_user() === false) {
4835                 throw new ForbiddenException();
4836         }
4837
4838         // params
4839         $user_info = api_get_user();
4840         $searchstring = $_REQUEST['searchstring'] ?? '';
4841         $uid = $user_info['uid'];
4842
4843         // error if no searchstring specified
4844         if ($searchstring == "") {
4845                 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
4846                 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
4847         }
4848
4849         // get data for the specified searchstring
4850         $r = DBA::toArray(DBA::p(
4851                 "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",
4852                 $uid,
4853                 '%'.$searchstring.'%'
4854         ));
4855
4856         $profile_url = $user_info["url"];
4857
4858         // message if nothing was found
4859         if (!DBA::isResult($r)) {
4860                 $success = ['success' => false, 'search_results' => 'problem with query'];
4861         } elseif (count($r) == 0) {
4862                 $success = ['success' => false, 'search_results' => 'nothing found'];
4863         } else {
4864                 $ret = [];
4865                 foreach ($r as $item) {
4866                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
4867                                 $recipient = $user_info;
4868                                 $sender = api_get_user(Strings::normaliseLink($item['contact-url']));
4869                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4870                                 $recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
4871                                 $sender = $user_info;
4872                         }
4873
4874                         if (isset($recipient) && isset($sender)) {
4875                                 $ret[] = api_format_messages($item, $recipient, $sender);
4876                         }
4877                 }
4878                 $success = ['success' => true, 'search_results' => $ret];
4879         }
4880
4881         return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
4882 }
4883
4884 /// @TODO move to top of file or somewhere better
4885 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4886
4887 /*
4888  * Number of comments
4889  *
4890  * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
4891  *
4892  * @param object $data [Status, Status]
4893  *
4894  * @return void
4895  */
4896 function bindComments(&$data)
4897 {
4898         if (count($data) == 0) {
4899                 return;
4900         }
4901
4902         $ids = [];
4903         $comments = [];
4904         foreach ($data as $item) {
4905                 $ids[] = $item['id'];
4906         }
4907
4908         $idStr = DBA::escape(implode(', ', $ids));
4909         $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
4910         $items = DBA::p($sql, 0, GRAVITY_COMMENT);
4911         $itemsData = DBA::toArray($items);
4912
4913         foreach ($itemsData as $item) {
4914                 $comments[$item['parent']] = $item['comments'];
4915         }
4916
4917         foreach ($data as $idx => $item) {
4918                 $id = $item['id'];
4919                 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
4920         }
4921 }
4922
4923 /*
4924 @TODO Maybe open to implement?
4925 To.Do:
4926         [pagename] => api/1.1/statuses/lookup.json
4927         [id] => 605138389168451584
4928         [include_cards] => true
4929         [cards_platform] => Android-12
4930         [include_entities] => true
4931         [include_my_retweet] => 1
4932         [include_rts] => 1
4933         [include_reply_count] => true
4934         [include_descendent_reply_count] => true
4935 (?)
4936
4937
4938 Not implemented by now:
4939 statuses/retweets_of_me
4940 friendships/create
4941 friendships/destroy
4942 friendships/exists
4943 friendships/show
4944 account/update_location
4945 account/update_profile_background_image
4946 blocks/create
4947 blocks/destroy
4948 friendica/profile/update
4949 friendica/profile/create
4950 friendica/profile/delete
4951
4952 Not implemented in status.net:
4953 statuses/retweeted_to_me
4954 statuses/retweeted_by_me
4955 direct_messages/destroy
4956 account/end_session
4957 account/update_delivery_device
4958 notifications/follow
4959 notifications/leave
4960 blocks/exists
4961 blocks/blocking
4962 lists
4963 */