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