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