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