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