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