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