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