]> git.mxchange.org Git - friendica.git/blob - include/api.php
7e32a43ad6cede3e9d5da9721ecd90f022af6e4f
[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\Notification;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Post;
45 use Friendica\Model\User;
46 use Friendica\Model\Verb;
47 use Friendica\Network\HTTPException;
48 use Friendica\Network\HTTPException\BadRequestException;
49 use Friendica\Network\HTTPException\ExpectationFailedException;
50 use Friendica\Network\HTTPException\ForbiddenException;
51 use Friendica\Network\HTTPException\InternalServerErrorException;
52 use Friendica\Network\HTTPException\MethodNotAllowedException;
53 use Friendica\Network\HTTPException\NotFoundException;
54 use Friendica\Network\HTTPException\TooManyRequestsException;
55 use Friendica\Network\HTTPException\UnauthorizedException;
56 use Friendica\Object\Image;
57 use Friendica\Protocol\Activity;
58 use Friendica\Protocol\Diaspora;
59 use Friendica\Security\FKOAuth1;
60 use Friendica\Security\OAuth1\OAuthRequest;
61 use Friendica\Security\OAuth1\OAuthUtil;
62 use Friendica\Util\DateTimeFormat;
63 use Friendica\Util\Images;
64 use Friendica\Util\Network;
65 use Friendica\Util\Proxy as ProxyUtils;
66 use Friendica\Util\Strings;
67 use Friendica\Util\XML;
68
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->getCommand(), ".xml") > 0) {
315                 $type = "xml";
316         }
317         if (strpos($args->getCommand(), ".json") > 0) {
318                 $type = "json";
319         }
320         if (strpos($args->getCommand(), ".rss") > 0) {
321                 $type = "rss";
322         }
323         if (strpos($args->getCommand(), ".atom") > 0) {
324                 $type = "atom";
325         }
326
327         try {
328                 foreach ($API as $p => $info) {
329                         if (strpos($args->getCommand(), $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 NotFoundException();
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 = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1122                         $posts_day = Post::count($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 = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1136                         $posts_week = Post::count($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 = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1150                         $posts_month = Post::count($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 = Post::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 = Post::select([], ['id' => $id]);
1586                 }
1587         }
1588
1589         $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1590
1591         $data['status'] = api_format_items(Post::toArray($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 `id` > ?",
1646                 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1647
1648         if ($max_id > 0) {
1649                 $condition[0] .= " AND `id` <= ?";
1650                 $condition[] = $max_id;
1651         }
1652         if ($exclude_replies) {
1653                 $condition[0] .= ' AND `gravity` = ?';
1654                 $condition[] = GRAVITY_PARENT;
1655         }
1656         if ($conversation_id > 0) {
1657                 $condition[0] .= " AND `parent` = ?";
1658                 $condition[] = $conversation_id;
1659         }
1660
1661         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1662         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1663
1664         $items = Post::toArray($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 = Post::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 `iid` <= ?";
1739                         $condition[] = $max_id;
1740                 }
1741
1742                 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1743                 $statuses = Post::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1744
1745                 $r = Post::toArray($statuses);
1746         } else {
1747                 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1748                         GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1749
1750                 if ($max_id > 0) {
1751                         $condition[0] .= " AND `id` <= ?";
1752                         $condition[] = $max_id;
1753                 }
1754                 if ($conversation_id > 0) {
1755                         $condition[0] .= " AND `parent` = ?";
1756                         $condition[] = $conversation_id;
1757                 }
1758
1759                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1760                 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1761
1762                 $r = Post::toArray($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 `id` > ? AND `private` = ?",
1814                 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1815
1816         if ($max_id > 0) {
1817                 $condition[0] .= " AND `id` <= ?";
1818                 $condition[] = $max_id;
1819         }
1820
1821         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1822         $statuses = Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1823 if (empty($statuses)) {
1824         return ['test' => $statuses, 'condition' => $condition, 'params' => $params, 'db' => DBA::errorNo(), 'msg' => DBA::errorMessage()];
1825 }
1826         $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1827
1828         bindComments($ret);
1829
1830         $data = ['status' => $ret];
1831         switch ($type) {
1832                 case "atom":
1833                         break;
1834                 case "rss":
1835                         $data = api_rss_extra($a, $data, $user_info);
1836                         break;
1837         }
1838
1839         return api_format_data("statuses", $type, $data);
1840 }
1841
1842 /// @TODO move to top of file or somewhere better
1843 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1844
1845 /**
1846  * Returns a single status.
1847  *
1848  * @param string $type Return type (atom, rss, xml, json)
1849  *
1850  * @return array|string
1851  * @throws BadRequestException
1852  * @throws ForbiddenException
1853  * @throws ImagickException
1854  * @throws InternalServerErrorException
1855  * @throws UnauthorizedException
1856  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1857  */
1858 function api_statuses_show($type)
1859 {
1860         $a = DI::app();
1861         $user_info = api_get_user($a);
1862
1863         if (api_user() === false || $user_info === false) {
1864                 throw new ForbiddenException();
1865         }
1866
1867         // params
1868         $id = intval($a->argv[3] ?? 0);
1869
1870         if ($id == 0) {
1871                 $id = intval($_REQUEST['id'] ?? 0);
1872         }
1873
1874         // Hotot workaround
1875         if ($id == 0) {
1876                 $id = intval($a->argv[4] ?? 0);
1877         }
1878
1879         Logger::log('API: api_statuses_show: ' . $id);
1880
1881         $conversation = !empty($_REQUEST['conversation']);
1882
1883         // try to fetch the item for the local user - or the public item, if there is no local one
1884         $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1885         if (!DBA::isResult($uri_item)) {
1886                 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1887         }
1888
1889         $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1890         if (!DBA::isResult($item)) {
1891                 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1892         }
1893
1894         $id = $item['id'];
1895
1896         if ($conversation) {
1897                 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1898                 $params = ['order' => ['id' => true]];
1899         } else {
1900                 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1901                 $params = [];
1902         }
1903
1904         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1905
1906         /// @TODO How about copying this to above methods which don't check $r ?
1907         if (!DBA::isResult($statuses)) {
1908                 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1909         }
1910
1911         $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1912
1913         if ($conversation) {
1914                 $data = ['status' => $ret];
1915                 return api_format_data("statuses", $type, $data);
1916         } else {
1917                 $data = ['status' => $ret[0]];
1918                 return api_format_data("status", $type, $data);
1919         }
1920 }
1921
1922 /// @TODO move to top of file or somewhere better
1923 api_register_func('api/statuses/show', 'api_statuses_show', true);
1924
1925 /**
1926  *
1927  * @param string $type Return type (atom, rss, xml, json)
1928  *
1929  * @return array|string
1930  * @throws BadRequestException
1931  * @throws ForbiddenException
1932  * @throws ImagickException
1933  * @throws InternalServerErrorException
1934  * @throws UnauthorizedException
1935  * @todo nothing to say?
1936  */
1937 function api_conversation_show($type)
1938 {
1939         $a = DI::app();
1940         $user_info = api_get_user($a);
1941
1942         if (api_user() === false || $user_info === false) {
1943                 throw new ForbiddenException();
1944         }
1945
1946         // params
1947         $id       = intval($a->argv[3]           ?? 0);
1948         $since_id = intval($_REQUEST['since_id'] ?? 0);
1949         $max_id   = intval($_REQUEST['max_id']   ?? 0);
1950         $count    = intval($_REQUEST['count']    ?? 20);
1951         $page     = intval($_REQUEST['page']     ?? 1);
1952
1953         $start = max(0, ($page - 1) * $count);
1954
1955         if ($id == 0) {
1956                 $id = intval($_REQUEST['id'] ?? 0);
1957         }
1958
1959         // Hotot workaround
1960         if ($id == 0) {
1961                 $id = intval($a->argv[4] ?? 0);
1962         }
1963
1964         Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1965
1966         // try to fetch the item for the local user - or the public item, if there is no local one
1967         $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1968         if (!DBA::isResult($item)) {
1969                 throw new BadRequestException("There is no status with this id.");
1970         }
1971
1972         $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1973         if (!DBA::isResult($parent)) {
1974                 throw new BadRequestException("There is no status with this id.");
1975         }
1976
1977         $id = $parent['id'];
1978
1979         $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1980                 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1981
1982         if ($max_id > 0) {
1983                 $condition[0] .= " AND `id` <= ?";
1984                 $condition[] = $max_id;
1985         }
1986
1987         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1988         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1989
1990         if (!DBA::isResult($statuses)) {
1991                 throw new BadRequestException("There is no status with id $id.");
1992         }
1993
1994         $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1995
1996         $data = ['status' => $ret];
1997         return api_format_data("statuses", $type, $data);
1998 }
1999
2000 /// @TODO move to top of file or somewhere better
2001 api_register_func('api/conversation/show', 'api_conversation_show', true);
2002 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2003
2004 /**
2005  * Repeats a status.
2006  *
2007  * @param string $type Return type (atom, rss, xml, json)
2008  *
2009  * @return array|string
2010  * @throws BadRequestException
2011  * @throws ForbiddenException
2012  * @throws ImagickException
2013  * @throws InternalServerErrorException
2014  * @throws UnauthorizedException
2015  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2016  */
2017 function api_statuses_repeat($type)
2018 {
2019         global $called_api;
2020
2021         $a = DI::app();
2022
2023         if (api_user() === false) {
2024                 throw new ForbiddenException();
2025         }
2026
2027         api_get_user($a);
2028
2029         // params
2030         $id = intval($a->argv[3] ?? 0);
2031
2032         if ($id == 0) {
2033                 $id = intval($_REQUEST['id'] ?? 0);
2034         }
2035
2036         // Hotot workaround
2037         if ($id == 0) {
2038                 $id = intval($a->argv[4] ?? 0);
2039         }
2040
2041         Logger::log('API: api_statuses_repeat: '.$id);
2042
2043         $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2044         $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2045  
2046         if (DBA::isResult($item) && !empty($item['body'])) {
2047                 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2048                         if (!Item::performActivity($id, 'announce', local_user())) {
2049                                 throw new InternalServerErrorException();
2050                         }
2051                 
2052                         $item_id = $id;
2053                 } else {
2054                         if (strpos($item['body'], "[/share]") !== false) {
2055                                 $pos = strpos($item['body'], "[share");
2056                                 $post = substr($item['body'], $pos);
2057                         } else {
2058                                 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2059
2060                                 if (!empty($item['title'])) {
2061                                         $post .= '[h3]' . $item['title'] . "[/h3]\n";
2062                                 }
2063
2064                                 $post .= $item['body'];
2065                                 $post .= "[/share]";
2066                         }
2067                         $_REQUEST['body'] = $post;
2068                         $_REQUEST['profile_uid'] = api_user();
2069                         $_REQUEST['api_source'] = true;
2070
2071                         if (empty($_REQUEST['source'])) {
2072                                 $_REQUEST["source"] = api_source();
2073                         }
2074
2075                         $item_id = item_post($a);
2076                 }
2077         } else {
2078                 throw new ForbiddenException();
2079         }
2080
2081         // output the post that we just posted.
2082         $called_api = [];
2083         return api_status_show($type, $item_id);
2084 }
2085
2086 /// @TODO move to top of file or somewhere better
2087 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2088
2089 /**
2090  * Destroys a specific status.
2091  *
2092  * @param string $type Return type (atom, rss, xml, json)
2093  *
2094  * @return array|string
2095  * @throws BadRequestException
2096  * @throws ForbiddenException
2097  * @throws ImagickException
2098  * @throws InternalServerErrorException
2099  * @throws UnauthorizedException
2100  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2101  */
2102 function api_statuses_destroy($type)
2103 {
2104         $a = DI::app();
2105
2106         if (api_user() === false) {
2107                 throw new ForbiddenException();
2108         }
2109
2110         api_get_user($a);
2111
2112         // params
2113         $id = intval($a->argv[3] ?? 0);
2114
2115         if ($id == 0) {
2116                 $id = intval($_REQUEST['id'] ?? 0);
2117         }
2118
2119         // Hotot workaround
2120         if ($id == 0) {
2121                 $id = intval($a->argv[4] ?? 0);
2122         }
2123
2124         Logger::log('API: api_statuses_destroy: '.$id);
2125
2126         $ret = api_statuses_show($type);
2127
2128         Item::deleteForUser(['id' => $id], api_user());
2129
2130         return $ret;
2131 }
2132
2133 /// @TODO move to top of file or somewhere better
2134 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2135
2136 /**
2137  * Returns the most recent mentions.
2138  *
2139  * @param string $type Return type (atom, rss, xml, json)
2140  *
2141  * @return array|string
2142  * @throws BadRequestException
2143  * @throws ForbiddenException
2144  * @throws ImagickException
2145  * @throws InternalServerErrorException
2146  * @throws UnauthorizedException
2147  * @see http://developer.twitter.com/doc/get/statuses/mentions
2148  */
2149 function api_statuses_mentions($type)
2150 {
2151         $a = DI::app();
2152         $user_info = api_get_user($a);
2153
2154         if (api_user() === false || $user_info === false) {
2155                 throw new ForbiddenException();
2156         }
2157
2158         unset($_REQUEST["user_id"]);
2159         unset($_GET["user_id"]);
2160
2161         unset($_REQUEST["screen_name"]);
2162         unset($_GET["screen_name"]);
2163
2164         // get last network messages
2165
2166         // params
2167         $since_id = intval($_REQUEST['since_id'] ?? 0);
2168         $max_id   = intval($_REQUEST['max_id']   ?? 0);
2169         $count    = intval($_REQUEST['count']    ?? 20);
2170         $page     = intval($_REQUEST['page']     ?? 1);
2171
2172         $start = max(0, ($page - 1) * $count);
2173
2174         $query = "`gravity` IN (?, ?) AND `uri-id` IN
2175                 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
2176                 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
2177
2178         $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2179                 Post\UserNotification::NOTIF_EXPLICIT_TAGGED | Post\UserNotification::NOTIF_IMPLICIT_TAGGED |
2180                 Post\UserNotification::NOTIF_THREAD_COMMENT | Post\UserNotification::NOTIF_DIRECT_COMMENT |
2181                 Post\UserNotification::NOTIF_DIRECT_THREAD_COMMENT,
2182                 api_user(), $since_id];
2183
2184         if ($max_id > 0) {
2185                 $query .= " AND `id` <= ?";
2186                 $condition[] = $max_id;
2187         }
2188
2189         array_unshift($condition, $query);
2190
2191         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2192         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2193
2194         $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2195
2196         $data = ['status' => $ret];
2197         switch ($type) {
2198                 case "atom":
2199                         break;
2200                 case "rss":
2201                         $data = api_rss_extra($a, $data, $user_info);
2202                         break;
2203         }
2204
2205         return api_format_data("statuses", $type, $data);
2206 }
2207
2208 /// @TODO move to top of file or somewhere better
2209 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2210 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2211
2212 /**
2213  * Returns the most recent statuses posted by the user.
2214  *
2215  * @param string $type Either "json" or "xml"
2216  * @return string|array
2217  * @throws BadRequestException
2218  * @throws ForbiddenException
2219  * @throws ImagickException
2220  * @throws InternalServerErrorException
2221  * @throws UnauthorizedException
2222  * @see   https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2223  */
2224 function api_statuses_user_timeline($type)
2225 {
2226         $a = DI::app();
2227         $user_info = api_get_user($a);
2228
2229         if (api_user() === false || $user_info === false) {
2230                 throw new ForbiddenException();
2231         }
2232
2233         Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2234
2235         $since_id        = $_REQUEST['since_id'] ?? 0;
2236         $max_id          = $_REQUEST['max_id'] ?? 0;
2237         $exclude_replies = !empty($_REQUEST['exclude_replies']);
2238         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2239
2240         // pagination
2241         $count = $_REQUEST['count'] ?? 20;
2242         $page  = $_REQUEST['page'] ?? 1;
2243
2244         $start = max(0, ($page - 1) * $count);
2245
2246         $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2247                 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2248
2249         if ($user_info['self'] == 1) {
2250                 $condition[0] .= ' AND `wall` ';
2251         }
2252
2253         if ($exclude_replies) {
2254                 $condition[0] .= ' AND `gravity` = ?';
2255                 $condition[] = GRAVITY_PARENT;
2256         }
2257
2258         if ($conversation_id > 0) {
2259                 $condition[0] .= " AND `parent` = ?";
2260                 $condition[] = $conversation_id;
2261         }
2262
2263         if ($max_id > 0) {
2264                 $condition[0] .= " AND `id` <= ?";
2265                 $condition[] = $max_id;
2266         }
2267
2268         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2269         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2270
2271         $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2272
2273         bindComments($ret);
2274
2275         $data = ['status' => $ret];
2276         switch ($type) {
2277                 case "atom":
2278                         break;
2279                 case "rss":
2280                         $data = api_rss_extra($a, $data, $user_info);
2281                         break;
2282         }
2283
2284         return api_format_data("statuses", $type, $data);
2285 }
2286
2287 /// @TODO move to top of file or somewhere better
2288 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2289
2290 /**
2291  * Star/unstar an item.
2292  * param: id : id of the item
2293  *
2294  * @param string $type Return type (atom, rss, xml, json)
2295  *
2296  * @return array|string
2297  * @throws BadRequestException
2298  * @throws ForbiddenException
2299  * @throws ImagickException
2300  * @throws InternalServerErrorException
2301  * @throws UnauthorizedException
2302  * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2303  */
2304 function api_favorites_create_destroy($type)
2305 {
2306         $a = DI::app();
2307
2308         if (api_user() === false) {
2309                 throw new ForbiddenException();
2310         }
2311
2312         // for versioned api.
2313         /// @TODO We need a better global soluton
2314         $action_argv_id = 2;
2315         if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2316                 $action_argv_id = 3;
2317         }
2318
2319         if ($a->argc <= $action_argv_id) {
2320                 throw new BadRequestException("Invalid request.");
2321         }
2322         $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2323         if ($a->argc == $action_argv_id + 2) {
2324                 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2325         } else {
2326                 $itemid = intval($_REQUEST['id'] ?? 0);
2327         }
2328
2329         $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2330
2331         if (!DBA::isResult($item)) {
2332                 throw new BadRequestException("Invalid item.");
2333         }
2334
2335         switch ($action) {
2336                 case "create":
2337                         $item['starred'] = 1;
2338                         break;
2339                 case "destroy":
2340                         $item['starred'] = 0;
2341                         break;
2342                 default:
2343                         throw new BadRequestException("Invalid action ".$action);
2344         }
2345
2346         $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2347
2348         if ($r === false) {
2349                 throw new InternalServerErrorException("DB error");
2350         }
2351
2352
2353         $user_info = api_get_user($a);
2354         $rets = api_format_items([$item], $user_info, false, $type);
2355         $ret = $rets[0];
2356
2357         $data = ['status' => $ret];
2358         switch ($type) {
2359                 case "atom":
2360                         break;
2361                 case "rss":
2362                         $data = api_rss_extra($a, $data, $user_info);
2363                         break;
2364         }
2365
2366         return api_format_data("status", $type, $data);
2367 }
2368
2369 /// @TODO move to top of file or somewhere better
2370 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2371 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2372
2373 /**
2374  * Returns the most recent favorite statuses.
2375  *
2376  * @param string $type Return type (atom, rss, xml, json)
2377  *
2378  * @return string|array
2379  * @throws BadRequestException
2380  * @throws ForbiddenException
2381  * @throws ImagickException
2382  * @throws InternalServerErrorException
2383  * @throws UnauthorizedException
2384  */
2385 function api_favorites($type)
2386 {
2387         global $called_api;
2388
2389         $a = DI::app();
2390         $user_info = api_get_user($a);
2391
2392         if (api_user() === false || $user_info === false) {
2393                 throw new ForbiddenException();
2394         }
2395
2396         $called_api = [];
2397
2398         // in friendica starred item are private
2399         // return favorites only for self
2400         Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2401
2402         if ($user_info['self'] == 0) {
2403                 $ret = [];
2404         } else {
2405                 // params
2406                 $since_id = $_REQUEST['since_id'] ?? 0;
2407                 $max_id = $_REQUEST['max_id'] ?? 0;
2408                 $count = $_GET['count'] ?? 20;
2409                 $page = $_REQUEST['page'] ?? 1;
2410
2411                 $start = max(0, ($page - 1) * $count);
2412
2413                 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2414                         api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2415
2416                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2417
2418                 if ($max_id > 0) {
2419                         $condition[0] .= " AND `id` <= ?";
2420                         $condition[] = $max_id;
2421                 }
2422
2423                 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2424
2425                 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2426         }
2427
2428         bindComments($ret);
2429
2430         $data = ['status' => $ret];
2431         switch ($type) {
2432                 case "atom":
2433                         break;
2434                 case "rss":
2435                         $data = api_rss_extra($a, $data, $user_info);
2436                         break;
2437         }
2438
2439         return api_format_data("statuses", $type, $data);
2440 }
2441
2442 /// @TODO move to top of file or somewhere better
2443 api_register_func('api/favorites', 'api_favorites', true);
2444
2445 /**
2446  *
2447  * @param array $item
2448  * @param array $recipient
2449  * @param array $sender
2450  *
2451  * @return array
2452  * @throws InternalServerErrorException
2453  */
2454 function api_format_messages($item, $recipient, $sender)
2455 {
2456         // standard meta information
2457         $ret = [
2458                 'id'                    => $item['id'],
2459                 'sender_id'             => $sender['id'],
2460                 'text'                  => "",
2461                 'recipient_id'          => $recipient['id'],
2462                 'created_at'            => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2463                 'sender_screen_name'    => $sender['screen_name'],
2464                 'recipient_screen_name' => $recipient['screen_name'],
2465                 'sender'                => $sender,
2466                 'recipient'             => $recipient,
2467                 'title'                 => "",
2468                 'friendica_seen'        => $item['seen'] ?? 0,
2469                 'friendica_parent_uri'  => $item['parent-uri'] ?? '',
2470         ];
2471
2472         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2473         if (isset($ret['sender']['uid'])) {
2474                 unset($ret['sender']['uid']);
2475         }
2476         if (isset($ret['sender']['self'])) {
2477                 unset($ret['sender']['self']);
2478         }
2479         if (isset($ret['recipient']['uid'])) {
2480                 unset($ret['recipient']['uid']);
2481         }
2482         if (isset($ret['recipient']['self'])) {
2483                 unset($ret['recipient']['self']);
2484         }
2485
2486         //don't send title to regular StatusNET requests to avoid confusing these apps
2487         if (!empty($_GET['getText'])) {
2488                 $ret['title'] = $item['title'];
2489                 if ($_GET['getText'] == 'html') {
2490                         $ret['text'] = BBCode::convert($item['body'], false);
2491                 } elseif ($_GET['getText'] == 'plain') {
2492                         $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
2493                 }
2494         } else {
2495                 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
2496         }
2497         if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2498                 unset($ret['sender']);
2499                 unset($ret['recipient']);
2500         }
2501
2502         return $ret;
2503 }
2504
2505 /**
2506  *
2507  * @param array $item
2508  *
2509  * @return array
2510  * @throws InternalServerErrorException
2511  */
2512 function api_convert_item($item)
2513 {
2514         $body = $item['body'];
2515         $entities = api_get_entitities($statustext, $body);
2516
2517         // Add pictures to the attachment array and remove them from the body
2518         $attachments = api_get_attachments($body);
2519
2520         // Workaround for ostatus messages where the title is identically to the body
2521         $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
2522         $statusbody = trim(HTML::toPlaintext($html, 0));
2523
2524         // handle data: images
2525         $statusbody = api_format_items_embeded_images($item, $statusbody);
2526
2527         $statustitle = trim($item['title']);
2528
2529         if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2530                 $statustext = trim($statusbody);
2531         } else {
2532                 $statustext = trim($statustitle."\n\n".$statusbody);
2533         }
2534
2535         if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2536                 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2537         }
2538
2539         $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2540
2541         // Workaround for clients with limited HTML parser functionality
2542         $search = ["<br>", "<blockquote>", "</blockquote>",
2543                         "<h1>", "</h1>", "<h2>", "</h2>",
2544                         "<h3>", "</h3>", "<h4>", "</h4>",
2545                         "<h5>", "</h5>", "<h6>", "</h6>"];
2546         $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2547                         "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2548                         "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2549                         "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2550         $statushtml = str_replace($search, $replace, $statushtml);
2551
2552         if ($item['title'] != "") {
2553                 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2554         }
2555
2556         do {
2557                 $oldtext = $statushtml;
2558                 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2559         } while ($oldtext != $statushtml);
2560
2561         if (substr($statushtml, 0, 4) == '<br>') {
2562                 $statushtml = substr($statushtml, 4);
2563         }
2564
2565         if (substr($statushtml, 0, -4) == '<br>') {
2566                 $statushtml = substr($statushtml, -4);
2567         }
2568
2569         // feeds without body should contain the link
2570         if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2571                 $statushtml .= BBCode::convert($item['plink']);
2572         }
2573
2574         return [
2575                 "text" => $statustext,
2576                 "html" => $statushtml,
2577                 "attachments" => $attachments,
2578                 "entities" => $entities
2579         ];
2580 }
2581
2582 /**
2583  *
2584  * @param string $body
2585  *
2586  * @return array
2587  * @throws InternalServerErrorException
2588  */
2589 function api_get_attachments(&$body)
2590 {
2591         $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2592         $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2593
2594         $URLSearchString = "^\[\]";
2595         if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2596                 return [];
2597         }
2598
2599         // Remove all embedded pictures, since they are added as attachments
2600         foreach ($images[0] as $orig) {
2601                 $body = str_replace($orig, '', $body);
2602         }
2603
2604         $attachments = [];
2605
2606         foreach ($images[1] as $image) {
2607                 $imagedata = Images::getInfoFromURLCached($image);
2608
2609                 if ($imagedata) {
2610                         $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2611                 }
2612         }
2613
2614         return $attachments;
2615 }
2616
2617 /**
2618  *
2619  * @param string $text
2620  * @param string $bbcode
2621  *
2622  * @return array
2623  * @throws InternalServerErrorException
2624  * @todo Links at the first character of the post
2625  */
2626 function api_get_entitities(&$text, $bbcode)
2627 {
2628         $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2629
2630         if ($include_entities != "true") {
2631                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2632
2633                 foreach ($images[1] as $image) {
2634                         $replace = ProxyUtils::proxifyUrl($image);
2635                         $text = str_replace($image, $replace, $text);
2636                 }
2637                 return [];
2638         }
2639
2640         $bbcode = BBCode::cleanPictureLinks($bbcode);
2641
2642         // Change pure links in text to bbcode uris
2643         $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2644
2645         $entities = [];
2646         $entities["hashtags"] = [];
2647         $entities["symbols"] = [];
2648         $entities["urls"] = [];
2649         $entities["user_mentions"] = [];
2650
2651         $URLSearchString = "^\[\]";
2652
2653         $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2654
2655         $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2656         $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2657
2658         $bbcode = preg_replace(
2659                 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2660                 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2661                 $bbcode
2662         );
2663         $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2664
2665         $bbcode = preg_replace(
2666                 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2667                 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2668                 $bbcode
2669         );
2670         $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2671
2672         $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2673
2674         preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2675
2676         $ordered_urls = [];
2677         foreach ($urls[1] as $id => $url) {
2678                 $start = iconv_strpos($text, $url, 0, "UTF-8");
2679                 if (!($start === false)) {
2680                         $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2681                 }
2682         }
2683
2684         ksort($ordered_urls);
2685
2686         $offset = 0;
2687
2688         foreach ($ordered_urls as $url) {
2689                 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2690                         && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2691                 ) {
2692                         $display_url = $url["title"];
2693                 } else {
2694                         $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2695                         $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2696
2697                         if (strlen($display_url) > 26) {
2698                                 $display_url = substr($display_url, 0, 25)."…";
2699                         }
2700                 }
2701
2702                 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2703                 if (!($start === false)) {
2704                         $entities["urls"][] = ["url" => $url["url"],
2705                                                         "expanded_url" => $url["url"],
2706                                                         "display_url" => $display_url,
2707                                                         "indices" => [$start, $start+strlen($url["url"])]];
2708                         $offset = $start + 1;
2709                 }
2710         }
2711
2712         preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2713         $ordered_images = [];
2714         foreach ($images as $image) {
2715                 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2716                 if (!($start === false)) {
2717                         $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2718                 }
2719         }
2720
2721         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2722         foreach ($images[1] as $image) {
2723                 $start = iconv_strpos($text, $image, 0, "UTF-8");
2724                 if (!($start === false)) {
2725                         $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2726                 }
2727         }
2728
2729         $offset = 0;
2730
2731         foreach ($ordered_images as $image) {
2732                 $url = $image['url'];
2733                 $ext_alt_text = $image['alt'];
2734
2735                 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2736                 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2737
2738                 if (strlen($display_url) > 26) {
2739                         $display_url = substr($display_url, 0, 25)."…";
2740                 }
2741
2742                 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2743                 if (!($start === false)) {
2744                         $image = Images::getInfoFromURLCached($url);
2745                         if ($image) {
2746                                 // If image cache is activated, then use the following sizes:
2747                                 // thumb  (150), small (340), medium (600) and large (1024)
2748                                 if (!DI::config()->get("system", "proxy_disabled")) {
2749                                         $media_url = ProxyUtils::proxifyUrl($url);
2750
2751                                         $sizes = [];
2752                                         $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2753                                         $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2754
2755                                         if (($image[0] > 150) || ($image[1] > 150)) {
2756                                                 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2757                                                 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2758                                         }
2759
2760                                         $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2761                                         $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2762
2763                                         if (($image[0] > 600) || ($image[1] > 600)) {
2764                                                 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2765                                                 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2766                                         }
2767                                 } else {
2768                                         $media_url = $url;
2769                                         $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2770                                 }
2771
2772                                 $entities["media"][] = [
2773                                                         "id" => $start+1,
2774                                                         "id_str" => (string) ($start + 1),
2775                                                         "indices" => [$start, $start+strlen($url)],
2776                                                         "media_url" => Strings::normaliseLink($media_url),
2777                                                         "media_url_https" => $media_url,
2778                                                         "url" => $url,
2779                                                         "display_url" => $display_url,
2780                                                         "expanded_url" => $url,
2781                                                         "ext_alt_text" => $ext_alt_text,
2782                                                         "type" => "photo",
2783                                                         "sizes" => $sizes];
2784                         }
2785                         $offset = $start + 1;
2786                 }
2787         }
2788
2789         return $entities;
2790 }
2791
2792 /**
2793  *
2794  * @param array $item
2795  * @param string $text
2796  *
2797  * @return string
2798  */
2799 function api_format_items_embeded_images($item, $text)
2800 {
2801         $text = preg_replace_callback(
2802                 '|data:image/([^;]+)[^=]+=*|m',
2803                 function () use ($item) {
2804                         return DI::baseUrl() . '/display/' . $item['guid'];
2805                 },
2806                 $text
2807         );
2808         return $text;
2809 }
2810
2811 /**
2812  * return <a href='url'>name</a> as array
2813  *
2814  * @param string $txt text
2815  * @return array
2816  *                      'name' => 'name',
2817  *                      'url => 'url'
2818  */
2819 function api_contactlink_to_array($txt)
2820 {
2821         $match = [];
2822         $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2823         if ($r && count($match)==3) {
2824                 $res = [
2825                         'name' => $match[2],
2826                         'url' => $match[1]
2827                 ];
2828         } else {
2829                 $res = [
2830                         'name' => $txt,
2831                         'url' => ""
2832                 ];
2833         }
2834         return $res;
2835 }
2836
2837
2838 /**
2839  * return likes, dislikes and attend status for item
2840  *
2841  * @param array  $item array
2842  * @param string $type Return type (atom, rss, xml, json)
2843  *
2844  * @return array
2845  *            likes => int count,
2846  *            dislikes => int count
2847  * @throws BadRequestException
2848  * @throws ImagickException
2849  * @throws InternalServerErrorException
2850  * @throws UnauthorizedException
2851  */
2852 function api_format_items_activities($item, $type = "json")
2853 {
2854         $a = DI::app();
2855
2856         $activities = [
2857                 'like' => [],
2858                 'dislike' => [],
2859                 'attendyes' => [],
2860                 'attendno' => [],
2861                 'attendmaybe' => [],
2862                 'announce' => [],
2863         ];
2864
2865         $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2866         $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2867
2868         while ($parent_item = Post::fetch($ret)) {
2869                 // not used as result should be structured like other user data
2870                 //builtin_activity_puller($i, $activities);
2871
2872                 // get user data and add it to the array of the activity
2873                 $user = api_get_user($a, $parent_item['author-id']);
2874                 switch ($parent_item['verb']) {
2875                         case Activity::LIKE:
2876                                 $activities['like'][] = $user;
2877                                 break;
2878                         case Activity::DISLIKE:
2879                                 $activities['dislike'][] = $user;
2880                                 break;
2881                         case Activity::ATTEND:
2882                                 $activities['attendyes'][] = $user;
2883                                 break;
2884                         case Activity::ATTENDNO:
2885                                 $activities['attendno'][] = $user;
2886                                 break;
2887                         case Activity::ATTENDMAYBE:
2888                                 $activities['attendmaybe'][] = $user;
2889                                 break;
2890                         case Activity::ANNOUNCE:
2891                                 $activities['announce'][] = $user;
2892                                 break;
2893                         default:
2894                                 break;
2895                 }
2896         }
2897
2898         DBA::close($ret);
2899
2900         if ($type == "xml") {
2901                 $xml_activities = [];
2902                 foreach ($activities as $k => $v) {
2903                         // change xml element from "like" to "friendica:like"
2904                         $xml_activities["friendica:".$k] = $v;
2905                         // add user data into xml output
2906                         $k_user = 0;
2907                         foreach ($v as $user) {
2908                                 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2909                         }
2910                 }
2911                 $activities = $xml_activities;
2912         }
2913
2914         return $activities;
2915 }
2916
2917 /**
2918  * format items to be returned by api
2919  *
2920  * @param array  $items       array of items
2921  * @param array  $user_info
2922  * @param bool   $filter_user filter items by $user_info
2923  * @param string $type        Return type (atom, rss, xml, json)
2924  * @return array
2925  * @throws BadRequestException
2926  * @throws ImagickException
2927  * @throws InternalServerErrorException
2928  * @throws UnauthorizedException
2929  */
2930 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2931 {
2932         $a = Friendica\DI::app();
2933
2934         $ret = [];
2935
2936         if (empty($items)) {
2937                 return $ret;
2938         }
2939
2940         foreach ((array)$items as $item) {
2941                 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2942
2943                 // Look if the posts are matching if they should be filtered by user id
2944                 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2945                         continue;
2946                 }
2947
2948                 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2949
2950                 $ret[] = $status;
2951         }
2952
2953         return $ret;
2954 }
2955
2956 /**
2957  * @param array  $item       Item record
2958  * @param string $type       Return format (atom, rss, xml, json)
2959  * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2960  * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2961  * @param array $owner_user  User record of the item owner, can be provided by api_item_get_user()
2962  * @return array API-formatted status
2963  * @throws BadRequestException
2964  * @throws ImagickException
2965  * @throws InternalServerErrorException
2966  * @throws UnauthorizedException
2967  */
2968 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2969 {
2970         $a = Friendica\DI::app();
2971
2972         if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2973                 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2974         }
2975
2976         localize_item($item);
2977
2978         $in_reply_to = api_in_reply_to($item);
2979
2980         $converted = api_convert_item($item);
2981
2982         if ($type == "xml") {
2983                 $geo = "georss:point";
2984         } else {
2985                 $geo = "geo";
2986         }
2987
2988         $status = [
2989                 'text'          => $converted["text"],
2990                 'truncated' => false,
2991                 'created_at'=> api_date($item['created']),
2992                 'in_reply_to_status_id' => $in_reply_to['status_id'],
2993                 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2994                 'source'    => (($item['app']) ? $item['app'] : 'web'),
2995                 'id'            => intval($item['id']),
2996                 'id_str'        => (string) intval($item['id']),
2997                 'in_reply_to_user_id' => $in_reply_to['user_id'],
2998                 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2999                 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3000                 $geo => null,
3001                 'favorited' => $item['starred'] ? true : false,
3002                 'user' =>  $status_user,
3003                 'friendica_author' => $author_user,
3004                 'friendica_owner' => $owner_user,
3005                 'friendica_private' => $item['private'] == Item::PRIVATE,
3006                 //'entities' => NULL,
3007                 'statusnet_html' => $converted["html"],
3008                 'statusnet_conversation_id' => $item['parent'],
3009                 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3010                 'friendica_activities' => api_format_items_activities($item, $type),
3011                 'friendica_title' => $item['title'],
3012                 'friendica_html' => BBCode::convert($item['body'], false)
3013         ];
3014
3015         if (count($converted["attachments"]) > 0) {
3016                 $status["attachments"] = $converted["attachments"];
3017         }
3018
3019         if (count($converted["entities"]) > 0) {
3020                 $status["entities"] = $converted["entities"];
3021         }
3022
3023         if ($status["source"] == 'web') {
3024                 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3025         } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3026                 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3027         }
3028
3029         $retweeted_item = [];
3030         $quoted_item = [];
3031
3032         if ($item['gravity'] == GRAVITY_PARENT) {
3033                 $body = $item['body'];
3034                 $retweeted_item = api_share_as_retweet($item);
3035                 if ($body != $item['body']) {
3036                         $quoted_item = $retweeted_item;
3037                         $retweeted_item = [];
3038                 }
3039         }
3040
3041         if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3042                 $announce = api_get_announce($item);
3043                 if (!empty($announce)) {
3044                         $retweeted_item = $item;
3045                         $item = $announce;
3046                         $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3047                 }
3048         }
3049
3050         if (!empty($quoted_item)) {
3051                 if ($quoted_item['id'] != $item['id']) {
3052                         $quoted_status = api_format_item($quoted_item);
3053                         /// @todo Only remove the attachments that are also contained in the quotes status
3054                         unset($status['attachments']);
3055                         unset($status['entities']);
3056                 } else {
3057                         $conv_quoted = api_convert_item($quoted_item);
3058                         $quoted_status = $status;
3059                         unset($quoted_status['attachments']);
3060                         unset($quoted_status['entities']);
3061                         unset($quoted_status['statusnet_conversation_id']);
3062                         $quoted_status['text'] = $conv_quoted['text'];
3063                         $quoted_status['statusnet_html'] = $conv_quoted['html'];
3064                         try {
3065                                 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3066                         } catch (BadRequestException $e) {
3067                                 // user not found. should be found?
3068                                 /// @todo check if the user should be always found
3069                                 $quoted_status["user"] = [];
3070                         }
3071                 }
3072                 unset($quoted_status['friendica_author']);
3073                 unset($quoted_status['friendica_owner']);
3074                 unset($quoted_status['friendica_activities']);
3075                 unset($quoted_status['friendica_private']);
3076         }
3077
3078         if (!empty($retweeted_item)) {
3079                 $retweeted_status = $status;
3080                 unset($retweeted_status['friendica_author']);
3081                 unset($retweeted_status['friendica_owner']);
3082                 unset($retweeted_status['friendica_activities']);
3083                 unset($retweeted_status['friendica_private']);
3084                 unset($retweeted_status['statusnet_conversation_id']);
3085                 $status['user'] = $status['friendica_owner'];
3086                 try {
3087                         $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3088                 } catch (BadRequestException $e) {
3089                         // user not found. should be found?
3090                         /// @todo check if the user should be always found
3091                         $retweeted_status["user"] = [];
3092                 }
3093
3094                 $rt_converted = api_convert_item($retweeted_item);
3095
3096                 $retweeted_status['text'] = $rt_converted["text"];
3097                 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3098                 $retweeted_status['created_at'] =  api_date($retweeted_item['created']);
3099
3100                 if (!empty($quoted_status)) {
3101                         $retweeted_status['quoted_status'] = $quoted_status;
3102                 }
3103
3104                 $status['friendica_author'] = $retweeted_status['user'];
3105                 $status['retweeted_status'] = $retweeted_status;
3106         } elseif (!empty($quoted_status)) {
3107                 $root_status = api_convert_item($item);
3108
3109                 $status['text'] = $root_status["text"];
3110                 $status['statusnet_html'] = $root_status["html"];
3111                 $status['quoted_status'] = $quoted_status;
3112         }
3113
3114         // "uid" and "self" are only needed for some internal stuff, so remove it from here
3115         unset($status["user"]["uid"]);
3116         unset($status["user"]["self"]);
3117
3118         if ($item["coord"] != "") {
3119                 $coords = explode(' ', $item["coord"]);
3120                 if (count($coords) == 2) {
3121                         if ($type == "json") {
3122                                 $status["geo"] = ['type' => 'Point',
3123                                         'coordinates' => [(float) $coords[0],
3124                                                 (float) $coords[1]]];
3125                         } else {// Not sure if this is the official format - if someone founds a documentation we can check
3126                                 $status["georss:point"] = $item["coord"];
3127                         }
3128                 }
3129         }
3130
3131         return $status;
3132 }
3133
3134 /**
3135  * Returns the remaining number of API requests available to the user before the API limit is reached.
3136  *
3137  * @param string $type Return type (atom, rss, xml, json)
3138  *
3139  * @return array|string
3140  * @throws Exception
3141  */
3142 function api_account_rate_limit_status($type)
3143 {
3144         if ($type == "xml") {
3145                 $hash = [
3146                                 'remaining-hits' => '150',
3147                                 '@attributes' => ["type" => "integer"],
3148                                 'hourly-limit' => '150',
3149                                 '@attributes2' => ["type" => "integer"],
3150                                 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3151                                 '@attributes3' => ["type" => "datetime"],
3152                                 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3153                                 '@attributes4' => ["type" => "integer"],
3154                         ];
3155         } else {
3156                 $hash = [
3157                                 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3158                                 'remaining_hits' => '150',
3159                                 'hourly_limit' => '150',
3160                                 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3161                         ];
3162         }
3163
3164         return api_format_data('hash', $type, ['hash' => $hash]);
3165 }
3166
3167 /// @TODO move to top of file or somewhere better
3168 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3169
3170 /**
3171  * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3172  *
3173  * @param string $type Return type (atom, rss, xml, json)
3174  *
3175  * @return array|string
3176  */
3177 function api_help_test($type)
3178 {
3179         if ($type == 'xml') {
3180                 $ok = "true";
3181         } else {
3182                 $ok = "ok";
3183         }
3184
3185         return api_format_data('ok', $type, ["ok" => $ok]);
3186 }
3187
3188 /// @TODO move to top of file or somewhere better
3189 api_register_func('api/help/test', 'api_help_test', false);
3190
3191 /**
3192  * Returns all lists the user subscribes to.
3193  *
3194  * @param string $type Return type (atom, rss, xml, json)
3195  *
3196  * @return array|string
3197  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3198  */
3199 function api_lists_list($type)
3200 {
3201         $ret = [];
3202         /// @TODO $ret is not filled here?
3203         return api_format_data('lists', $type, ["lists_list" => $ret]);
3204 }
3205
3206 /// @TODO move to top of file or somewhere better
3207 api_register_func('api/lists/list', 'api_lists_list', true);
3208 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3209
3210 /**
3211  * Returns all groups the user owns.
3212  *
3213  * @param string $type Return type (atom, rss, xml, json)
3214  *
3215  * @return array|string
3216  * @throws BadRequestException
3217  * @throws ForbiddenException
3218  * @throws ImagickException
3219  * @throws InternalServerErrorException
3220  * @throws UnauthorizedException
3221  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3222  */
3223 function api_lists_ownerships($type)
3224 {
3225         $a = DI::app();
3226
3227         if (api_user() === false) {
3228                 throw new ForbiddenException();
3229         }
3230
3231         // params
3232         $user_info = api_get_user($a);
3233         $uid = $user_info['uid'];
3234
3235         $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3236
3237         // loop through all groups
3238         $lists = [];
3239         foreach ($groups as $group) {
3240                 if ($group['visible']) {
3241                         $mode = 'public';
3242                 } else {
3243                         $mode = 'private';
3244                 }
3245                 $lists[] = [
3246                         'name' => $group['name'],
3247                         'id' => intval($group['id']),
3248                         'id_str' => (string) $group['id'],
3249                         'user' => $user_info,
3250                         'mode' => $mode
3251                 ];
3252         }
3253         return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3254 }
3255
3256 /// @TODO move to top of file or somewhere better
3257 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3258
3259 /**
3260  * Returns recent statuses from users in the specified group.
3261  *
3262  * @param string $type Return type (atom, rss, xml, json)
3263  *
3264  * @return array|string
3265  * @throws BadRequestException
3266  * @throws ForbiddenException
3267  * @throws ImagickException
3268  * @throws InternalServerErrorException
3269  * @throws UnauthorizedException
3270  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3271  */
3272 function api_lists_statuses($type)
3273 {
3274         $a = DI::app();
3275
3276         $user_info = api_get_user($a);
3277         if (api_user() === false || $user_info === false) {
3278                 throw new ForbiddenException();
3279         }
3280
3281         unset($_REQUEST["user_id"]);
3282         unset($_GET["user_id"]);
3283
3284         unset($_REQUEST["screen_name"]);
3285         unset($_GET["screen_name"]);
3286
3287         if (empty($_REQUEST['list_id'])) {
3288                 throw new BadRequestException('list_id not specified');
3289         }
3290
3291         // params
3292         $count = $_REQUEST['count'] ?? 20;
3293         $page = $_REQUEST['page'] ?? 1;
3294         $since_id = $_REQUEST['since_id'] ?? 0;
3295         $max_id = $_REQUEST['max_id'] ?? 0;
3296         $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3297         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3298
3299         $start = max(0, ($page - 1) * $count);
3300
3301         $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3302         $gids = array_column($groups, 'contact-id');
3303         $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3304         $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3305
3306         if ($max_id > 0) {
3307                 $condition[0] .= " AND `id` <= ?";
3308                 $condition[] = $max_id;
3309         }
3310         if ($exclude_replies > 0) {
3311                 $condition[0] .= ' AND `gravity` = ?';
3312                 $condition[] = GRAVITY_PARENT;
3313         }
3314         if ($conversation_id > 0) {
3315                 $condition[0] .= " AND `parent` = ?";
3316                 $condition[] = $conversation_id;
3317         }
3318
3319         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3320         $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3321
3322         $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3323
3324         $data = ['status' => $items];
3325         switch ($type) {
3326                 case "atom":
3327                         break;
3328                 case "rss":
3329                         $data = api_rss_extra($a, $data, $user_info);
3330                         break;
3331         }
3332
3333         return api_format_data("statuses", $type, $data);
3334 }
3335
3336 /// @TODO move to top of file or somewhere better
3337 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3338
3339 /**
3340  * Returns either the friends of the follower list
3341  *
3342  * Considers friends and followers lists to be private and won't return
3343  * anything if any user_id parameter is passed.
3344  *
3345  * @param string $qtype Either "friends" or "followers"
3346  * @return boolean|array
3347  * @throws BadRequestException
3348  * @throws ForbiddenException
3349  * @throws ImagickException
3350  * @throws InternalServerErrorException
3351  * @throws UnauthorizedException
3352  */
3353 function api_statuses_f($qtype)
3354 {
3355         $a = DI::app();
3356
3357         if (api_user() === false) {
3358                 throw new ForbiddenException();
3359         }
3360
3361         // pagination
3362         $count = $_GET['count'] ?? 20;
3363         $page = $_GET['page'] ?? 1;
3364
3365         $start = max(0, ($page - 1) * $count);
3366
3367         $user_info = api_get_user($a);
3368
3369         if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3370                 /* this is to stop Hotot to load friends multiple times
3371                 *  I'm not sure if I'm missing return something or
3372                 *  is a bug in hotot. Workaround, meantime
3373                 */
3374
3375                 /*$ret=Array();
3376                 return array('$users' => $ret);*/
3377                 return false;
3378         }
3379
3380         $sql_extra = '';
3381         if ($qtype == 'friends') {
3382                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3383         } elseif ($qtype == 'followers') {
3384                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3385         }
3386
3387         // friends and followers only for self
3388         if ($user_info['self'] == 0) {
3389                 $sql_extra = " AND false ";
3390         }
3391
3392         if ($qtype == 'blocks') {
3393                 $sql_filter = 'AND `blocked` AND NOT `pending`';
3394         } elseif ($qtype == 'incoming') {
3395                 $sql_filter = 'AND `pending`';
3396         } else {
3397                 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3398         }
3399
3400         $r = q(
3401                 "SELECT `nurl`
3402                 FROM `contact`
3403                 WHERE `uid` = %d
3404                 AND NOT `self`
3405                 $sql_filter
3406                 $sql_extra
3407                 ORDER BY `nick`
3408                 LIMIT %d, %d",
3409                 intval(api_user()),
3410                 intval($start),
3411                 intval($count)
3412         );
3413
3414         $ret = [];
3415         foreach ($r as $cid) {
3416                 $user = api_get_user($a, $cid['nurl']);
3417                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3418                 unset($user["uid"]);
3419                 unset($user["self"]);
3420
3421                 if ($user) {
3422                         $ret[] = $user;
3423                 }
3424         }
3425
3426         return ['user' => $ret];
3427 }
3428
3429
3430 /**
3431  * Returns the list of friends of the provided user
3432  *
3433  * @deprecated By Twitter API in favor of friends/list
3434  *
3435  * @param string $type Either "json" or "xml"
3436  * @return boolean|string|array
3437  * @throws BadRequestException
3438  * @throws ForbiddenException
3439  */
3440 function api_statuses_friends($type)
3441 {
3442         $data =  api_statuses_f("friends");
3443         if ($data === false) {
3444                 return false;
3445         }
3446         return api_format_data("users", $type, $data);
3447 }
3448
3449 /**
3450  * Returns the list of followers of the provided user
3451  *
3452  * @deprecated By Twitter API in favor of friends/list
3453  *
3454  * @param string $type Either "json" or "xml"
3455  * @return boolean|string|array
3456  * @throws BadRequestException
3457  * @throws ForbiddenException
3458  */
3459 function api_statuses_followers($type)
3460 {
3461         $data = api_statuses_f("followers");
3462         if ($data === false) {
3463                 return false;
3464         }
3465         return api_format_data("users", $type, $data);
3466 }
3467
3468 /// @TODO move to top of file or somewhere better
3469 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3470 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3471
3472 /**
3473  * Returns the list of blocked users
3474  *
3475  * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3476  *
3477  * @param string $type Either "json" or "xml"
3478  *
3479  * @return boolean|string|array
3480  * @throws BadRequestException
3481  * @throws ForbiddenException
3482  */
3483 function api_blocks_list($type)
3484 {
3485         $data =  api_statuses_f('blocks');
3486         if ($data === false) {
3487                 return false;
3488         }
3489         return api_format_data("users", $type, $data);
3490 }
3491
3492 /// @TODO move to top of file or somewhere better
3493 api_register_func('api/blocks/list', 'api_blocks_list', true);
3494
3495 /**
3496  * Returns the list of pending users IDs
3497  *
3498  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3499  *
3500  * @param string $type Either "json" or "xml"
3501  *
3502  * @return boolean|string|array
3503  * @throws BadRequestException
3504  * @throws ForbiddenException
3505  */
3506 function api_friendships_incoming($type)
3507 {
3508         $data =  api_statuses_f('incoming');
3509         if ($data === false) {
3510                 return false;
3511         }
3512
3513         $ids = [];
3514         foreach ($data['user'] as $user) {
3515                 $ids[] = $user['id'];
3516         }
3517
3518         return api_format_data("ids", $type, ['id' => $ids]);
3519 }
3520
3521 /// @TODO move to top of file or somewhere better
3522 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3523
3524 /**
3525  * Returns the instance's configuration information.
3526  *
3527  * @param string $type Return type (atom, rss, xml, json)
3528  *
3529  * @return array|string
3530  * @throws InternalServerErrorException
3531  */
3532 function api_statusnet_config($type)
3533 {
3534         $name      = DI::config()->get('config', 'sitename');
3535         $server    = DI::baseUrl()->getHostname();
3536         $logo      = DI::baseUrl() . '/images/friendica-64.png';
3537         $email     = DI::config()->get('config', 'admin_email');
3538         $closed    = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3539         $private   = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3540         $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3541         $ssl       = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3542         $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3543
3544         $config = [
3545                 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3546                         'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3547                         'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3548                         'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3549                         'shorturllength' => '30',
3550                         'friendica' => [
3551                                         'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3552                                         'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3553                                         'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3554                                         'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3555                                         ]
3556                 ],
3557         ];
3558
3559         return api_format_data('config', $type, ['config' => $config]);
3560 }
3561
3562 /// @TODO move to top of file or somewhere better
3563 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3564 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3565
3566 /**
3567  *
3568  * @param string $type Return type (atom, rss, xml, json)
3569  *
3570  * @return array|string
3571  */
3572 function api_statusnet_version($type)
3573 {
3574         // liar
3575         $fake_statusnet_version = "0.9.7";
3576
3577         return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3578 }
3579
3580 /// @TODO move to top of file or somewhere better
3581 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3582 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3583
3584 /**
3585  * Sends a new direct message.
3586  *
3587  * @param string $type Return type (atom, rss, xml, json)
3588  *
3589  * @return array|string
3590  * @throws BadRequestException
3591  * @throws ForbiddenException
3592  * @throws ImagickException
3593  * @throws InternalServerErrorException
3594  * @throws NotFoundException
3595  * @throws UnauthorizedException
3596  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3597  */
3598 function api_direct_messages_new($type)
3599 {
3600         $a = DI::app();
3601
3602         if (api_user() === false) {
3603                 throw new ForbiddenException();
3604         }
3605
3606         if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3607                 return;
3608         }
3609
3610         $sender = api_get_user($a);
3611
3612         $recipient = null;
3613         if (!empty($_POST['screen_name'])) {
3614                 $r = q(
3615                         "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3616                         intval(api_user()),
3617                         DBA::escape($_POST['screen_name'])
3618                 );
3619
3620                 if (DBA::isResult($r)) {
3621                         // Selecting the id by priority, friendica first
3622                         api_best_nickname($r);
3623
3624                         $recipient = api_get_user($a, $r[0]['nurl']);
3625                 }
3626         } else {
3627                 $recipient = api_get_user($a, $_POST['user_id']);
3628         }
3629
3630         if (empty($recipient)) {
3631                 throw new NotFoundException('Recipient not found');
3632         }
3633
3634         $replyto = '';
3635         if (!empty($_REQUEST['replyto'])) {
3636                 $r = q(
3637                         'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3638                         intval(api_user()),
3639                         intval($_REQUEST['replyto'])
3640                 );
3641                 $replyto = $r[0]['parent-uri'];
3642                 $sub     = $r[0]['title'];
3643         } else {
3644                 if (!empty($_REQUEST['title'])) {
3645                         $sub = $_REQUEST['title'];
3646                 } else {
3647                         $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3648                 }
3649         }
3650
3651         $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3652
3653         if ($id > -1) {
3654                 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3655                 $ret = api_format_messages($r[0], $recipient, $sender);
3656         } else {
3657                 $ret = ["error"=>$id];
3658         }
3659
3660         $data = ['direct_message'=>$ret];
3661
3662         switch ($type) {
3663                 case "atom":
3664                         break;
3665                 case "rss":
3666                         $data = api_rss_extra($a, $data, $sender);
3667                         break;
3668         }
3669
3670         return api_format_data("direct-messages", $type, $data);
3671 }
3672
3673 /// @TODO move to top of file or somewhere better
3674 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3675
3676 /**
3677  * delete a direct_message from mail table through api
3678  *
3679  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3680  * @return string|array
3681  * @throws BadRequestException
3682  * @throws ForbiddenException
3683  * @throws ImagickException
3684  * @throws InternalServerErrorException
3685  * @throws UnauthorizedException
3686  * @see   https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3687  */
3688 function api_direct_messages_destroy($type)
3689 {
3690         $a = DI::app();
3691
3692         if (api_user() === false) {
3693                 throw new ForbiddenException();
3694         }
3695
3696         // params
3697         $user_info = api_get_user($a);
3698         //required
3699         $id = $_REQUEST['id'] ?? 0;
3700         // optional
3701         $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3702         $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3703         /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3704
3705         $uid = $user_info['uid'];
3706         // error if no id or parenturi specified (for clients posting parent-uri as well)
3707         if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3708                 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3709                 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3710         }
3711
3712         // BadRequestException if no id specified (for clients using Twitter API)
3713         if ($id == 0) {
3714                 throw new BadRequestException('Message id not specified');
3715         }
3716
3717         // add parent-uri to sql command if specified by calling app
3718         $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3719
3720         // get data of the specified message id
3721         $r = q(
3722                 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3723                 intval($uid),
3724                 intval($id)
3725         );
3726
3727         // error message if specified id is not in database
3728         if (!DBA::isResult($r)) {
3729                 if ($verbose == "true") {
3730                         $answer = ['result' => 'error', 'message' => 'message id not in database'];
3731                         return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3732                 }
3733                 /// @todo BadRequestException ok for Twitter API clients?
3734                 throw new BadRequestException('message id not in database');
3735         }
3736
3737         // delete message
3738         $result = q(
3739                 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3740                 intval($uid),
3741                 intval($id)
3742         );
3743
3744         if ($verbose == "true") {
3745                 if ($result) {
3746                         // return success
3747                         $answer = ['result' => 'ok', 'message' => 'message deleted'];
3748                         return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3749                 } else {
3750                         $answer = ['result' => 'error', 'message' => 'unknown error'];
3751                         return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3752                 }
3753         }
3754         /// @todo return JSON data like Twitter API not yet implemented
3755 }
3756
3757 /// @TODO move to top of file or somewhere better
3758 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3759
3760 /**
3761  * Unfollow Contact
3762  *
3763  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3764  * @return string|array
3765  * @throws BadRequestException
3766  * @throws ForbiddenException
3767  * @throws ImagickException
3768  * @throws InternalServerErrorException
3769  * @throws NotFoundException
3770  * @see   https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3771  */
3772 function api_friendships_destroy($type)
3773 {
3774         $uid = api_user();
3775
3776         if ($uid === false) {
3777                 throw new ForbiddenException();
3778         }
3779
3780         $contact_id = $_REQUEST['user_id'] ?? 0;
3781
3782         if (empty($contact_id)) {
3783                 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3784                 throw new BadRequestException("no user_id specified");
3785         }
3786
3787         // Get Contact by given id
3788         $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3789
3790         if(!DBA::isResult($contact)) {
3791                 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3792                 throw new NotFoundException("no contact found to given ID");
3793         }
3794
3795         $url = $contact["url"];
3796
3797         $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3798                         $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3799                         Strings::normaliseLink($url), $url];
3800         $contact = DBA::selectFirst('contact', [], $condition);
3801
3802         if (!DBA::isResult($contact)) {
3803                 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3804                 throw new NotFoundException("Not following Contact");
3805         }
3806
3807         if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3808                 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3809                 throw new ExpectationFailedException("Not supported");
3810         }
3811
3812         $dissolve = ($contact['rel'] == Contact::SHARING);
3813
3814         $owner = User::getOwnerDataById($uid);
3815         if ($owner) {
3816                 Contact::terminateFriendship($owner, $contact, $dissolve);
3817         }
3818         else {
3819                 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3820                 throw new NotFoundException("Error Processing Request");
3821         }
3822
3823         // Sharing-only contacts get deleted as there no relationship any more
3824         if ($dissolve) {
3825                 Contact::remove($contact['id']);
3826         } else {
3827                 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3828         }
3829
3830         // "uid" and "self" are only needed for some internal stuff, so remove it from here
3831         unset($contact["uid"]);
3832         unset($contact["self"]);
3833
3834         // Set screen_name since Twidere requests it
3835         $contact["screen_name"] = $contact["nick"];
3836
3837         return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3838 }
3839 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3840
3841 /**
3842  *
3843  * @param string $type Return type (atom, rss, xml, json)
3844  * @param string $box
3845  * @param string $verbose
3846  *
3847  * @return array|string
3848  * @throws BadRequestException
3849  * @throws ForbiddenException
3850  * @throws ImagickException
3851  * @throws InternalServerErrorException
3852  * @throws UnauthorizedException
3853  */
3854 function api_direct_messages_box($type, $box, $verbose)
3855 {
3856         $a = DI::app();
3857         if (api_user() === false) {
3858                 throw new ForbiddenException();
3859         }
3860         // params
3861         $count = $_GET['count'] ?? 20;
3862         $page = $_REQUEST['page'] ?? 1;
3863
3864         $since_id = $_REQUEST['since_id'] ?? 0;
3865         $max_id = $_REQUEST['max_id'] ?? 0;
3866
3867         $user_id = $_REQUEST['user_id'] ?? '';
3868         $screen_name = $_REQUEST['screen_name'] ?? '';
3869
3870         //  caller user info
3871         unset($_REQUEST["user_id"]);
3872         unset($_GET["user_id"]);
3873
3874         unset($_REQUEST["screen_name"]);
3875         unset($_GET["screen_name"]);
3876
3877         $user_info = api_get_user($a);
3878         if ($user_info === false) {
3879                 throw new ForbiddenException();
3880         }
3881         $profile_url = $user_info["url"];
3882
3883         // pagination
3884         $start = max(0, ($page - 1) * $count);
3885
3886         $sql_extra = "";
3887
3888         // filters
3889         if ($box=="sentbox") {
3890                 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3891         } elseif ($box == "conversation") {
3892                 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '')  . "'";
3893         } elseif ($box == "all") {
3894                 $sql_extra = "true";
3895         } elseif ($box == "inbox") {
3896                 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3897         }
3898
3899         if ($max_id > 0) {
3900                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3901         }
3902
3903         if ($user_id != "") {
3904                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3905         } elseif ($screen_name !="") {
3906                 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3907         }
3908
3909         $r = q(
3910                 "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",
3911                 intval(api_user()),
3912                 intval($since_id),
3913                 intval($start),
3914                 intval($count)
3915         );
3916         if ($verbose == "true" && !DBA::isResult($r)) {
3917                 $answer = ['result' => 'error', 'message' => 'no mails available'];
3918                 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3919         }
3920
3921         $ret = [];
3922         foreach ($r as $item) {
3923                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3924                         $recipient = $user_info;
3925                         $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3926                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3927                         $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3928                         $sender = $user_info;
3929                 }
3930
3931                 if (isset($recipient) && isset($sender)) {
3932                         $ret[] = api_format_messages($item, $recipient, $sender);
3933                 }
3934         }
3935
3936
3937         $data = ['direct_message' => $ret];
3938         switch ($type) {
3939                 case "atom":
3940                         break;
3941                 case "rss":
3942                         $data = api_rss_extra($a, $data, $user_info);
3943                         break;
3944         }
3945
3946         return api_format_data("direct-messages", $type, $data);
3947 }
3948
3949 /**
3950  * Returns the most recent direct messages sent by the user.
3951  *
3952  * @param string $type Return type (atom, rss, xml, json)
3953  *
3954  * @return array|string
3955  * @throws BadRequestException
3956  * @throws ForbiddenException
3957  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3958  */
3959 function api_direct_messages_sentbox($type)
3960 {
3961         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3962         return api_direct_messages_box($type, "sentbox", $verbose);
3963 }
3964
3965 /**
3966  * Returns the most recent direct messages sent to the user.
3967  *
3968  * @param string $type Return type (atom, rss, xml, json)
3969  *
3970  * @return array|string
3971  * @throws BadRequestException
3972  * @throws ForbiddenException
3973  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3974  */
3975 function api_direct_messages_inbox($type)
3976 {
3977         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3978         return api_direct_messages_box($type, "inbox", $verbose);
3979 }
3980
3981 /**
3982  *
3983  * @param string $type Return type (atom, rss, xml, json)
3984  *
3985  * @return array|string
3986  * @throws BadRequestException
3987  * @throws ForbiddenException
3988  */
3989 function api_direct_messages_all($type)
3990 {
3991         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3992         return api_direct_messages_box($type, "all", $verbose);
3993 }
3994
3995 /**
3996  *
3997  * @param string $type Return type (atom, rss, xml, json)
3998  *
3999  * @return array|string
4000  * @throws BadRequestException
4001  * @throws ForbiddenException
4002  */
4003 function api_direct_messages_conversation($type)
4004 {
4005         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4006         return api_direct_messages_box($type, "conversation", $verbose);
4007 }
4008
4009 /// @TODO move to top of file or somewhere better
4010 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4011 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4012 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4013 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4014
4015 /**
4016  * Returns an OAuth Request Token.
4017  *
4018  * @see https://oauth.net/core/1.0/#auth_step1
4019  */
4020 function api_oauth_request_token()
4021 {
4022         $oauth1 = new FKOAuth1();
4023         try {
4024                 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4025         } catch (Exception $e) {
4026                 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4027                 exit();
4028         }
4029         echo $r;
4030         exit();
4031 }
4032
4033 /**
4034  * Returns an OAuth Access Token.
4035  *
4036  * @return array|string
4037  * @see https://oauth.net/core/1.0/#auth_step3
4038  */
4039 function api_oauth_access_token()
4040 {
4041         $oauth1 = new FKOAuth1();
4042         try {
4043                 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4044         } catch (Exception $e) {
4045                 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4046                 exit();
4047         }
4048         echo $r;
4049         exit();
4050 }
4051
4052 /// @TODO move to top of file or somewhere better
4053 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4054 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4055
4056
4057 /**
4058  * delete a complete photoalbum with all containing photos from database through api
4059  *
4060  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4061  * @return string|array
4062  * @throws BadRequestException
4063  * @throws ForbiddenException
4064  * @throws InternalServerErrorException
4065  */
4066 function api_fr_photoalbum_delete($type)
4067 {
4068         if (api_user() === false) {
4069                 throw new ForbiddenException();
4070         }
4071         // input params
4072         $album = $_REQUEST['album'] ?? '';
4073
4074         // we do not allow calls without album string
4075         if ($album == "") {
4076                 throw new BadRequestException("no albumname specified");
4077         }
4078         // check if album is existing
4079
4080         $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4081         if (!DBA::isResult($photos)) {
4082                 throw new BadRequestException("album not available");
4083         }
4084
4085         $resourceIds = array_column($photos, 'resource-id');
4086
4087         // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4088         // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4089         $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4090         Item::deleteForUser($condition, api_user());
4091
4092         // now let's delete all photos from the album
4093         $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4094
4095         // return success of deletion or error message
4096         if ($result) {
4097                 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4098                 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4099         } else {
4100                 throw new InternalServerErrorException("unknown error - deleting from database failed");
4101         }
4102 }
4103
4104 /**
4105  * update the name of the album for all photos of an album
4106  *
4107  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4108  * @return string|array
4109  * @throws BadRequestException
4110  * @throws ForbiddenException
4111  * @throws InternalServerErrorException
4112  */
4113 function api_fr_photoalbum_update($type)
4114 {
4115         if (api_user() === false) {
4116                 throw new ForbiddenException();
4117         }
4118         // input params
4119         $album = $_REQUEST['album'] ?? '';
4120         $album_new = $_REQUEST['album_new'] ?? '';
4121
4122         // we do not allow calls without album string
4123         if ($album == "") {
4124                 throw new BadRequestException("no albumname specified");
4125         }
4126         if ($album_new == "") {
4127                 throw new BadRequestException("no new albumname specified");
4128         }
4129         // check if album is existing
4130         if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4131                 throw new BadRequestException("album not available");
4132         }
4133         // now let's update all photos to the albumname
4134         $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4135
4136         // return success of updating or error message
4137         if ($result) {
4138                 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4139                 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4140         } else {
4141                 throw new InternalServerErrorException("unknown error - updating in database failed");
4142         }
4143 }
4144
4145
4146 /**
4147  * list all photos of the authenticated user
4148  *
4149  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4150  * @return string|array
4151  * @throws ForbiddenException
4152  * @throws InternalServerErrorException
4153  */
4154 function api_fr_photos_list($type)
4155 {
4156         if (api_user() === false) {
4157                 throw new ForbiddenException();
4158         }
4159         $r = q(
4160                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4161                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4162                 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4163                 intval(local_user())
4164         );
4165         $typetoext = [
4166                 'image/jpeg' => 'jpg',
4167                 'image/png' => 'png',
4168                 'image/gif' => 'gif'
4169         ];
4170         $data = ['photo'=>[]];
4171         if (DBA::isResult($r)) {
4172                 foreach ($r as $rr) {
4173                         $photo = [];
4174                         $photo['id'] = $rr['resource-id'];
4175                         $photo['album'] = $rr['album'];
4176                         $photo['filename'] = $rr['filename'];
4177                         $photo['type'] = $rr['type'];
4178                         $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4179                         $photo['created'] = $rr['created'];
4180                         $photo['edited'] = $rr['edited'];
4181                         $photo['desc'] = $rr['desc'];
4182
4183                         if ($type == "xml") {
4184                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4185                         } else {
4186                                 $photo['thumb'] = $thumb;
4187                                 $data['photo'][] = $photo;
4188                         }
4189                 }
4190         }
4191         return api_format_data("photos", $type, $data);
4192 }
4193
4194 /**
4195  * upload a new photo or change an existing photo
4196  *
4197  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4198  * @return string|array
4199  * @throws BadRequestException
4200  * @throws ForbiddenException
4201  * @throws ImagickException
4202  * @throws InternalServerErrorException
4203  * @throws NotFoundException
4204  */
4205 function api_fr_photo_create_update($type)
4206 {
4207         if (api_user() === false) {
4208                 throw new ForbiddenException();
4209         }
4210         // input params
4211         $photo_id  = $_REQUEST['photo_id']  ?? null;
4212         $desc      = $_REQUEST['desc']      ?? null;
4213         $album     = $_REQUEST['album']     ?? null;
4214         $album_new = $_REQUEST['album_new'] ?? null;
4215         $allow_cid = $_REQUEST['allow_cid'] ?? null;
4216         $deny_cid  = $_REQUEST['deny_cid' ] ?? null;
4217         $allow_gid = $_REQUEST['allow_gid'] ?? null;
4218         $deny_gid  = $_REQUEST['deny_gid' ] ?? null;
4219         $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4220
4221         // do several checks on input parameters
4222         // we do not allow calls without album string
4223         if ($album == null) {
4224                 throw new BadRequestException("no albumname specified");
4225         }
4226         // if photo_id == null --> we are uploading a new photo
4227         if ($photo_id == null) {
4228                 $mode = "create";
4229
4230                 // error if no media posted in create-mode
4231                 if (empty($_FILES['media'])) {
4232                         // Output error
4233                         throw new BadRequestException("no media data submitted");
4234                 }
4235
4236                 // album_new will be ignored in create-mode
4237                 $album_new = "";
4238         } else {
4239                 $mode = "update";
4240
4241                 // check if photo is existing in databasei
4242                 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4243                         throw new BadRequestException("photo not available");
4244                 }
4245         }
4246
4247         // checks on acl strings provided by clients
4248         $acl_input_error = false;
4249         $acl_input_error |= check_acl_input($allow_cid);
4250         $acl_input_error |= check_acl_input($deny_cid);
4251         $acl_input_error |= check_acl_input($allow_gid);
4252         $acl_input_error |= check_acl_input($deny_gid);
4253         if ($acl_input_error) {
4254                 throw new BadRequestException("acl data invalid");
4255         }
4256         // now let's upload the new media in create-mode
4257         if ($mode == "create") {
4258                 $media = $_FILES['media'];
4259                 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4260
4261                 // return success of updating or error message
4262                 if (!is_null($data)) {
4263                         return api_format_data("photo_create", $type, $data);
4264                 } else {
4265                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4266                 }
4267         }
4268
4269         // now let's do the changes in update-mode
4270         if ($mode == "update") {
4271                 $updated_fields = [];
4272
4273                 if (!is_null($desc)) {
4274                         $updated_fields['desc'] = $desc;
4275                 }
4276
4277                 if (!is_null($album_new)) {
4278                         $updated_fields['album'] = $album_new;
4279                 }
4280
4281                 if (!is_null($allow_cid)) {
4282                         $allow_cid = trim($allow_cid);
4283                         $updated_fields['allow_cid'] = $allow_cid;
4284                 }
4285
4286                 if (!is_null($deny_cid)) {
4287                         $deny_cid = trim($deny_cid);
4288                         $updated_fields['deny_cid'] = $deny_cid;
4289                 }
4290
4291                 if (!is_null($allow_gid)) {
4292                         $allow_gid = trim($allow_gid);
4293                         $updated_fields['allow_gid'] = $allow_gid;
4294                 }
4295
4296                 if (!is_null($deny_gid)) {
4297                         $deny_gid = trim($deny_gid);
4298                         $updated_fields['deny_gid'] = $deny_gid;
4299                 }
4300
4301                 $result = false;
4302                 if (count($updated_fields) > 0) {
4303                         $nothingtodo = false;
4304                         $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4305                 } else {
4306                         $nothingtodo = true;
4307                 }
4308
4309                 if (!empty($_FILES['media'])) {
4310                         $nothingtodo = false;
4311                         $media = $_FILES['media'];
4312                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4313                         if (!is_null($data)) {
4314                                 return api_format_data("photo_update", $type, $data);
4315                         }
4316                 }
4317
4318                 // return success of updating or error message
4319                 if ($result) {
4320                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4321                         return api_format_data("photo_update", $type, ['$result' => $answer]);
4322                 } else {
4323                         if ($nothingtodo) {
4324                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4325                                 return api_format_data("photo_update", $type, ['$result' => $answer]);
4326                         }
4327                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4328                 }
4329         }
4330         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4331 }
4332
4333 /**
4334  * delete a single photo from the database through api
4335  *
4336  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4337  * @return string|array
4338  * @throws BadRequestException
4339  * @throws ForbiddenException
4340  * @throws InternalServerErrorException
4341  */
4342 function api_fr_photo_delete($type)
4343 {
4344         if (api_user() === false) {
4345                 throw new ForbiddenException();
4346         }
4347
4348         // input params
4349         $photo_id = $_REQUEST['photo_id'] ?? null;
4350
4351         // do several checks on input parameters
4352         // we do not allow calls without photo id
4353         if ($photo_id == null) {
4354                 throw new BadRequestException("no photo_id specified");
4355         }
4356
4357         // check if photo is existing in database
4358         if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4359                 throw new BadRequestException("photo not available");
4360         }
4361
4362         // now we can perform on the deletion of the photo
4363         $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4364
4365         // return success of deletion or error message
4366         if ($result) {
4367                 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4368                 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4369                 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4370                 Item::deleteForUser($condition, api_user());
4371
4372                 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4373                 return api_format_data("photo_delete", $type, ['$result' => $result]);
4374         } else {
4375                 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4376         }
4377 }
4378
4379
4380 /**
4381  * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4382  *
4383  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4384  * @return string|array
4385  * @throws BadRequestException
4386  * @throws ForbiddenException
4387  * @throws InternalServerErrorException
4388  * @throws NotFoundException
4389  */
4390 function api_fr_photo_detail($type)
4391 {
4392         if (api_user() === false) {
4393                 throw new ForbiddenException();
4394         }
4395         if (empty($_REQUEST['photo_id'])) {
4396                 throw new BadRequestException("No photo id.");
4397         }
4398
4399         $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4400         $photo_id = $_REQUEST['photo_id'];
4401
4402         // prepare json/xml output with data from database for the requested photo
4403         $data = prepare_photo_data($type, $scale, $photo_id);
4404
4405         return api_format_data("photo_detail", $type, $data);
4406 }
4407
4408
4409 /**
4410  * updates the profile image for the user (either a specified profile or the default profile)
4411  *
4412  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4413  *
4414  * @return string|array
4415  * @throws BadRequestException
4416  * @throws ForbiddenException
4417  * @throws ImagickException
4418  * @throws InternalServerErrorException
4419  * @throws NotFoundException
4420  * @see   https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4421  */
4422 function api_account_update_profile_image($type)
4423 {
4424         if (api_user() === false) {
4425                 throw new ForbiddenException();
4426         }
4427         // input params
4428         $profile_id = $_REQUEST['profile_id'] ?? 0;
4429
4430         // error if image data is missing
4431         if (empty($_FILES['image'])) {
4432                 throw new BadRequestException("no media data submitted");
4433         }
4434
4435         // check if specified profile id is valid
4436         if ($profile_id != 0) {
4437                 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4438                 // error message if specified profile id is not in database
4439                 if (!DBA::isResult($profile)) {
4440                         throw new BadRequestException("profile_id not available");
4441                 }
4442                 $is_default_profile = $profile['is-default'];
4443         } else {
4444                 $is_default_profile = 1;
4445         }
4446
4447         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4448         $media = null;
4449         if (!empty($_FILES['image'])) {
4450                 $media = $_FILES['image'];
4451         } elseif (!empty($_FILES['media'])) {
4452                 $media = $_FILES['media'];
4453         }
4454         // save new profile image
4455         $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4456
4457         // get filetype
4458         if (is_array($media['type'])) {
4459                 $filetype = $media['type'][0];
4460         } else {
4461                 $filetype = $media['type'];
4462         }
4463         if ($filetype == "image/jpeg") {
4464                 $fileext = "jpg";
4465         } elseif ($filetype == "image/png") {
4466                 $fileext = "png";
4467         } else {
4468                 throw new InternalServerErrorException('Unsupported filetype');
4469         }
4470
4471         // change specified profile or all profiles to the new resource-id
4472         if ($is_default_profile) {
4473                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4474                 Photo::update(['profile' => false], $condition);
4475         } else {
4476                 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4477                         'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4478                 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4479         }
4480
4481         Contact::updateSelfFromUserID(api_user(), true);
4482
4483         // Update global directory in background
4484         $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4485         if ($url && strlen(DI::config()->get('system', 'directory'))) {
4486                 Worker::add(PRIORITY_LOW, "Directory", $url);
4487         }
4488
4489         Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4490
4491         // output for client
4492         if ($data) {
4493                 return api_account_verify_credentials($type);
4494         } else {
4495                 // SaveMediaToDatabase failed for some reason
4496                 throw new InternalServerErrorException("image upload failed");
4497         }
4498 }
4499
4500 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4501 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4502 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4503 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4504 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4505 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4506 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4507 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4508 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4509
4510 /**
4511  * Update user profile
4512  *
4513  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4514  *
4515  * @return array|string
4516  * @throws BadRequestException
4517  * @throws ForbiddenException
4518  * @throws ImagickException
4519  * @throws InternalServerErrorException
4520  * @throws UnauthorizedException
4521  */
4522 function api_account_update_profile($type)
4523 {
4524         $local_user = api_user();
4525         $api_user = api_get_user(DI::app());
4526
4527         if (!empty($_POST['name'])) {
4528                 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4529                 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4530                 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4531                 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4532         }
4533
4534         if (isset($_POST['description'])) {
4535                 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4536                 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4537                 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4538         }
4539
4540         Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4541         // Update global directory in background
4542         if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4543                 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4544         }
4545
4546         return api_account_verify_credentials($type);
4547 }
4548
4549 /// @TODO move to top of file or somewhere better
4550 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4551
4552 /**
4553  *
4554  * @param string $acl_string
4555  * @return bool
4556  * @throws Exception
4557  */
4558 function check_acl_input($acl_string)
4559 {
4560         if (empty($acl_string)) {
4561                 return false;
4562         }
4563
4564         $contact_not_found = false;
4565
4566         // split <x><y><z> into array of cid's
4567         preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4568
4569         // check for each cid if it is available on server
4570         $cid_array = $array[0];
4571         foreach ($cid_array as $cid) {
4572                 $cid = str_replace("<", "", $cid);
4573                 $cid = str_replace(">", "", $cid);
4574                 $condition = ['id' => $cid, 'uid' => api_user()];
4575                 $contact_not_found |= !DBA::exists('contact', $condition);
4576         }
4577         return $contact_not_found;
4578 }
4579
4580 /**
4581  * @param string  $mediatype
4582  * @param array   $media
4583  * @param string  $type
4584  * @param string  $album
4585  * @param string  $allow_cid
4586  * @param string  $deny_cid
4587  * @param string  $allow_gid
4588  * @param string  $deny_gid
4589  * @param string  $desc
4590  * @param integer $profile
4591  * @param boolean $visibility
4592  * @param string  $photo_id
4593  * @return array
4594  * @throws BadRequestException
4595  * @throws ForbiddenException
4596  * @throws ImagickException
4597  * @throws InternalServerErrorException
4598  * @throws NotFoundException
4599  * @throws UnauthorizedException
4600  */
4601 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)
4602 {
4603         $visitor   = 0;
4604         $src = "";
4605         $filetype = "";
4606         $filename = "";
4607         $filesize = 0;
4608
4609         if (is_array($media)) {
4610                 if (is_array($media['tmp_name'])) {
4611                         $src = $media['tmp_name'][0];
4612                 } else {
4613                         $src = $media['tmp_name'];
4614                 }
4615                 if (is_array($media['name'])) {
4616                         $filename = basename($media['name'][0]);
4617                 } else {
4618                         $filename = basename($media['name']);
4619                 }
4620                 if (is_array($media['size'])) {
4621                         $filesize = intval($media['size'][0]);
4622                 } else {
4623                         $filesize = intval($media['size']);
4624                 }
4625                 if (is_array($media['type'])) {
4626                         $filetype = $media['type'][0];
4627                 } else {
4628                         $filetype = $media['type'];
4629                 }
4630         }
4631
4632         $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4633
4634         Logger::log(
4635                 "File upload src: " . $src . " - filename: " . $filename .
4636                 " - size: " . $filesize . " - type: " . $filetype,
4637                 Logger::DEBUG
4638         );
4639
4640         // check if there was a php upload error
4641         if ($filesize == 0 && $media['error'] == 1) {
4642                 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4643         }
4644         // check against max upload size within Friendica instance
4645         $maximagesize = DI::config()->get('system', 'maximagesize');
4646         if ($maximagesize && ($filesize > $maximagesize)) {
4647                 $formattedBytes = Strings::formatBytes($maximagesize);
4648                 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4649         }
4650
4651         // create Photo instance with the data of the image
4652         $imagedata = @file_get_contents($src);
4653         $Image = new Image($imagedata, $filetype);
4654         if (!$Image->isValid()) {
4655                 throw new InternalServerErrorException("unable to process image data");
4656         }
4657
4658         // check orientation of image
4659         $Image->orient($src);
4660         @unlink($src);
4661
4662         // check max length of images on server
4663         $max_length = DI::config()->get('system', 'max_image_length');
4664         if (!$max_length) {
4665                 $max_length = MAX_IMAGE_LENGTH;
4666         }
4667         if ($max_length > 0) {
4668                 $Image->scaleDown($max_length);
4669                 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4670         }
4671         $width = $Image->getWidth();
4672         $height = $Image->getHeight();
4673
4674         // create a new resource-id if not already provided
4675         $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4676
4677         if ($mediatype == "photo") {
4678                 // upload normal image (scales 0, 1, 2)
4679                 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4680
4681                 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4682                 if (!$r) {
4683                         Logger::log("photo upload: image upload with scale 0 (original size) failed");
4684                 }
4685                 if ($width > 640 || $height > 640) {
4686                         $Image->scaleDown(640);
4687                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4688                         if (!$r) {
4689                                 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4690                         }
4691                 }
4692
4693                 if ($width > 320 || $height > 320) {
4694                         $Image->scaleDown(320);
4695                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4696                         if (!$r) {
4697                                 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4698                         }
4699                 }
4700                 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4701         } elseif ($mediatype == "profileimage") {
4702                 // upload profile image (scales 4, 5, 6)
4703                 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4704
4705                 if ($width > 300 || $height > 300) {
4706                         $Image->scaleDown(300);
4707                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4708                         if (!$r) {
4709                                 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4710                         }
4711                 }
4712
4713                 if ($width > 80 || $height > 80) {
4714                         $Image->scaleDown(80);
4715                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4716                         if (!$r) {
4717                                 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4718                         }
4719                 }
4720
4721                 if ($width > 48 || $height > 48) {
4722                         $Image->scaleDown(48);
4723                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4724                         if (!$r) {
4725                                 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4726                         }
4727                 }
4728                 $Image->__destruct();
4729                 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4730         }
4731
4732         if (!empty($r)) {
4733                 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4734                 if ($photo_id == null && $mediatype == "photo") {
4735                         post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4736                 }
4737                 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4738                 return prepare_photo_data($type, false, $resource_id);
4739         } else {
4740                 throw new InternalServerErrorException("image upload failed");
4741         }
4742 }
4743
4744 /**
4745  *
4746  * @param string  $hash
4747  * @param string  $allow_cid
4748  * @param string  $deny_cid
4749  * @param string  $allow_gid
4750  * @param string  $deny_gid
4751  * @param string  $filetype
4752  * @param boolean $visibility
4753  * @throws InternalServerErrorException
4754  */
4755 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4756 {
4757         // get data about the api authenticated user
4758         $uri = Item::newURI(intval(api_user()));
4759         $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4760
4761         $arr = [];
4762         $arr['guid']          = System::createUUID();
4763         $arr['uid']           = intval(api_user());
4764         $arr['uri']           = $uri;
4765         $arr['type']          = 'photo';
4766         $arr['wall']          = 1;
4767         $arr['resource-id']   = $hash;
4768         $arr['contact-id']    = $owner_record['id'];
4769         $arr['owner-name']    = $owner_record['name'];
4770         $arr['owner-link']    = $owner_record['url'];
4771         $arr['owner-avatar']  = $owner_record['thumb'];
4772         $arr['author-name']   = $owner_record['name'];
4773         $arr['author-link']   = $owner_record['url'];
4774         $arr['author-avatar'] = $owner_record['thumb'];
4775         $arr['title']         = "";
4776         $arr['allow_cid']     = $allow_cid;
4777         $arr['allow_gid']     = $allow_gid;
4778         $arr['deny_cid']      = $deny_cid;
4779         $arr['deny_gid']      = $deny_gid;
4780         $arr['visible']       = $visibility;
4781         $arr['origin']        = 1;
4782
4783         $typetoext = [
4784                         'image/jpeg' => 'jpg',
4785                         'image/png' => 'png',
4786                         'image/gif' => 'gif'
4787                         ];
4788
4789         // adds link to the thumbnail scale photo
4790         $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4791                                 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4792                                 . '[/url]';
4793
4794         // do the magic for storing the item in the database and trigger the federation to other contacts
4795         Item::insert($arr);
4796 }
4797
4798 /**
4799  *
4800  * @param string $type
4801  * @param int    $scale
4802  * @param string $photo_id
4803  *
4804  * @return array
4805  * @throws BadRequestException
4806  * @throws ForbiddenException
4807  * @throws ImagickException
4808  * @throws InternalServerErrorException
4809  * @throws NotFoundException
4810  * @throws UnauthorizedException
4811  */
4812 function prepare_photo_data($type, $scale, $photo_id)
4813 {
4814         $a = DI::app();
4815         $user_info = api_get_user($a);
4816
4817         if ($user_info === false) {
4818                 throw new ForbiddenException();
4819         }
4820
4821         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4822         $data_sql = ($scale === false ? "" : "data, ");
4823
4824         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4825         // clients needs to convert this in their way for further processing
4826         $r = q(
4827                 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4828                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4829                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4830                         FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY 
4831                                `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4832                                `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4833                 $data_sql,
4834                 intval(local_user()),
4835                 DBA::escape($photo_id),
4836                 $scale_sql
4837         );
4838
4839         $typetoext = [
4840                 'image/jpeg' => 'jpg',
4841                 'image/png' => 'png',
4842                 'image/gif' => 'gif'
4843         ];
4844
4845         // prepare output data for photo
4846         if (DBA::isResult($r)) {
4847                 $data = ['photo' => $r[0]];
4848                 $data['photo']['id'] = $data['photo']['resource-id'];
4849                 if ($scale !== false) {
4850                         $data['photo']['data'] = base64_encode($data['photo']['data']);
4851                 } else {
4852                         unset($data['photo']['datasize']); //needed only with scale param
4853                 }
4854                 if ($type == "xml") {
4855                         $data['photo']['links'] = [];
4856                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4857                                 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4858                                                                                 "scale" => $k,
4859                                                                                 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4860                         }
4861                 } else {
4862                         $data['photo']['link'] = [];
4863                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4864                         $i = 0;
4865                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4866                                 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4867                                 $i++;
4868                         }
4869                 }
4870                 unset($data['photo']['resource-id']);
4871                 unset($data['photo']['minscale']);
4872                 unset($data['photo']['maxscale']);
4873         } else {
4874                 throw new NotFoundException();
4875         }
4876
4877         // retrieve item element for getting activities (like, dislike etc.) related to photo
4878         $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4879         $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4880         if (!DBA::isResult($item)) {
4881                 throw new NotFoundException('Photo-related item not found.');
4882         }
4883
4884         $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4885
4886         // retrieve comments on photo
4887         $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4888                 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4889
4890         $statuses = Post::selectForUser(api_user(), [], $condition);
4891
4892         // prepare output of comments
4893         $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4894         $comments = [];
4895         if ($type == "xml") {
4896                 $k = 0;
4897                 foreach ($commentData as $comment) {
4898                         $comments[$k++ . ":comment"] = $comment;
4899                 }
4900         } else {
4901                 foreach ($commentData as $comment) {
4902                         $comments[] = $comment;
4903                 }
4904         }
4905         $data['photo']['friendica_comments'] = $comments;
4906
4907         // include info if rights on photo and rights on item are mismatching
4908         $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4909                 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4910                 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4911                 $data['photo']['deny_gid'] != $item['deny_gid'];
4912         $data['photo']['rights_mismatch'] = $rights_mismatch;
4913
4914         return $data;
4915 }
4916
4917
4918 /**
4919  * Similar as /mod/redir.php
4920  * redirect to 'url' after dfrn auth
4921  *
4922  * Why this when there is mod/redir.php already?
4923  * This use api_user() and api_login()
4924  *
4925  * params
4926  *              c_url: url of remote contact to auth to
4927  *              url: string, url to redirect after auth
4928  */
4929 function api_friendica_remoteauth()
4930 {
4931         $url = $_GET['url'] ?? '';
4932         $c_url = $_GET['c_url'] ?? '';
4933
4934         if ($url === '' || $c_url === '') {
4935                 throw new BadRequestException("Wrong parameters.");
4936         }
4937
4938         $c_url = Strings::normaliseLink($c_url);
4939
4940         // traditional DFRN
4941
4942         $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4943         if (!DBA::isResult($contact)) {
4944                 throw new BadRequestException("Unknown contact");
4945         }
4946
4947         $cid = $contact['id'];
4948
4949         $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
4950
4951         if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
4952                 System::externalRedirect($url ?: $c_url);
4953         }
4954
4955         if ($contact['duplex'] && $contact['issued-id']) {
4956                 $orig_id = $contact['issued-id'];
4957                 $dfrn_id = '1:' . $orig_id;
4958         }
4959         if ($contact['duplex'] && $contact['dfrn-id']) {
4960                 $orig_id = $contact['dfrn-id'];
4961                 $dfrn_id = '0:' . $orig_id;
4962         }
4963
4964         $sec = Strings::getRandomHex();
4965
4966         $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4967                 'sec' => $sec, 'expire' => time() + 45];
4968         DBA::insert('profile_check', $fields);
4969
4970         Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
4971         $dest = ($url ? '&destination_url=' . $url : '');
4972
4973         System::externalRedirect(
4974                 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4975                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4976                 . '&type=profile&sec=' . $sec . $dest
4977         );
4978 }
4979 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4980
4981 /**
4982  * Return an item with announcer data if it had been announced
4983  *
4984  * @param array $item Item array
4985  * @return array Item array with announce data
4986  */
4987 function api_get_announce($item)
4988 {
4989         // Quit if the item already has got a different owner and author
4990         if ($item['owner-id'] != $item['author-id']) {
4991                 return [];
4992         }
4993
4994         // Don't change original or Diaspora posts
4995         if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4996                 return [];
4997         }
4998
4999         // Quit if we do now the original author and it had been a post from a native network
5000         if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5001                 return [];
5002         }
5003
5004         $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5005         $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
5006         $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5007         if (!DBA::isResult($announce)) {
5008                 return [];
5009         }
5010
5011         return array_merge($item, $announce);
5012 }
5013
5014 /**
5015  * Return the item shared, if the item contains only the [share] tag
5016  *
5017  * @param array $item Sharer item
5018  * @return array|false Shared item or false if not a reshare
5019  * @throws ImagickException
5020  * @throws InternalServerErrorException
5021  */
5022 function api_share_as_retweet(&$item)
5023 {
5024         $body = trim($item["body"]);
5025
5026         if (Diaspora::isReshare($body, false) === false) {
5027                 if ($item['author-id'] == $item['owner-id']) {
5028                         return false;
5029                 } else {
5030                         // Reshares from OStatus, ActivityPub and Twitter
5031                         $reshared_item = $item;
5032                         $reshared_item['owner-id'] = $reshared_item['author-id'];
5033                         $reshared_item['owner-link'] = $reshared_item['author-link'];
5034                         $reshared_item['owner-name'] = $reshared_item['author-name'];
5035                         $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5036                         return $reshared_item;
5037                 }
5038         }
5039
5040         $reshared = Item::getShareArray($item);
5041         if (empty($reshared)) {
5042                 return false;
5043         }
5044
5045         $reshared_item = $item;
5046
5047         if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5048                 return false;
5049         }
5050
5051         if (!empty($reshared['comment'])) {
5052                 $item['body'] = $reshared['comment'];
5053         }
5054
5055         $reshared_item["share-pre-body"] = $reshared['comment'];
5056         $reshared_item["body"] = $reshared['shared'];
5057         $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, false);
5058         $reshared_item["author-name"] = $reshared['author'];
5059         $reshared_item["author-link"] = $reshared['profile'];
5060         $reshared_item["author-avatar"] = $reshared['avatar'];
5061         $reshared_item["plink"] = $reshared['link'] ?? '';
5062         $reshared_item["created"] = $reshared['posted'];
5063         $reshared_item["edited"] = $reshared['posted'];
5064
5065         // Try to fetch the original item
5066         if (!empty($reshared['guid'])) {
5067                 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5068         } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5069                 $condition = ['id' => $original_id];
5070         } else {
5071                 $condition = [];
5072         }
5073
5074         if (!empty($condition)) {
5075                 $original_item = Post::selectFirst([], $condition);
5076                 if (DBA::isResult($original_item)) {
5077                         $reshared_item = array_merge($reshared_item, $original_item);
5078                 }
5079         }
5080
5081         return $reshared_item;
5082 }
5083
5084 /**
5085  *
5086  * @param array $item
5087  *
5088  * @return array
5089  * @throws Exception
5090  */
5091 function api_in_reply_to($item)
5092 {
5093         $in_reply_to = [];
5094
5095         $in_reply_to['status_id'] = null;
5096         $in_reply_to['user_id'] = null;
5097         $in_reply_to['status_id_str'] = null;
5098         $in_reply_to['user_id_str'] = null;
5099         $in_reply_to['screen_name'] = null;
5100
5101         if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
5102                 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5103                 if (DBA::isResult($parent)) {
5104                         $in_reply_to['status_id'] = intval($parent['id']);
5105                 } else {
5106                         $in_reply_to['status_id'] = intval($item['parent']);
5107                 }
5108
5109                 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5110
5111                 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5112                 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5113
5114                 if (DBA::isResult($parent)) {
5115                         $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5116                         $in_reply_to['user_id'] = intval($parent['author-id']);
5117                         $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5118                 }
5119
5120                 // There seems to be situation, where both fields are identical:
5121                 // https://github.com/friendica/friendica/issues/1010
5122                 // This is a bugfix for that.
5123                 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5124                         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']]);
5125                         $in_reply_to['status_id'] = null;
5126                         $in_reply_to['user_id'] = null;
5127                         $in_reply_to['status_id_str'] = null;
5128                         $in_reply_to['user_id_str'] = null;
5129                         $in_reply_to['screen_name'] = null;
5130                 }
5131         }
5132
5133         return $in_reply_to;
5134 }
5135
5136 /**
5137  *
5138  * @param string $text
5139  *
5140  * @return string
5141  * @throws InternalServerErrorException
5142  */
5143 function api_clean_plain_items($text)
5144 {
5145         $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5146
5147         $text = BBCode::cleanPictureLinks($text);
5148         $URLSearchString = "^\[\]";
5149
5150         $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5151
5152         if ($include_entities == "true") {
5153                 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5154         }
5155
5156         // Simplify "attachment" element
5157         $text = BBCode::removeAttachment($text);
5158
5159         return $text;
5160 }
5161
5162 /**
5163  *
5164  * @param array $contacts
5165  *
5166  * @return void
5167  */
5168 function api_best_nickname(&$contacts)
5169 {
5170         $best_contact = [];
5171
5172         if (count($contacts) == 0) {
5173                 return;
5174         }
5175
5176         foreach ($contacts as $contact) {
5177                 if ($contact["network"] == "") {
5178                         $contact["network"] = "dfrn";
5179                         $best_contact = [$contact];
5180                 }
5181         }
5182
5183         if (sizeof($best_contact) == 0) {
5184                 foreach ($contacts as $contact) {
5185                         if ($contact["network"] == "dfrn") {
5186                                 $best_contact = [$contact];
5187                         }
5188                 }
5189         }
5190
5191         if (sizeof($best_contact) == 0) {
5192                 foreach ($contacts as $contact) {
5193                         if ($contact["network"] == "dspr") {
5194                                 $best_contact = [$contact];
5195                         }
5196                 }
5197         }
5198
5199         if (sizeof($best_contact) == 0) {
5200                 foreach ($contacts as $contact) {
5201                         if ($contact["network"] == "stat") {
5202                                 $best_contact = [$contact];
5203                         }
5204                 }
5205         }
5206
5207         if (sizeof($best_contact) == 0) {
5208                 foreach ($contacts as $contact) {
5209                         if ($contact["network"] == "pump") {
5210                                 $best_contact = [$contact];
5211                         }
5212                 }
5213         }
5214
5215         if (sizeof($best_contact) == 0) {
5216                 foreach ($contacts as $contact) {
5217                         if ($contact["network"] == "twit") {
5218                                 $best_contact = [$contact];
5219                         }
5220                 }
5221         }
5222
5223         if (sizeof($best_contact) == 1) {
5224                 $contacts = $best_contact;
5225         } else {
5226                 $contacts = [$contacts[0]];
5227         }
5228 }
5229
5230 /**
5231  * Return all or a specified group of the user with the containing contacts.
5232  *
5233  * @param string $type Return type (atom, rss, xml, json)
5234  *
5235  * @return array|string
5236  * @throws BadRequestException
5237  * @throws ForbiddenException
5238  * @throws ImagickException
5239  * @throws InternalServerErrorException
5240  * @throws UnauthorizedException
5241  */
5242 function api_friendica_group_show($type)
5243 {
5244         $a = DI::app();
5245
5246         if (api_user() === false) {
5247                 throw new ForbiddenException();
5248         }
5249
5250         // params
5251         $user_info = api_get_user($a);
5252         $gid = $_REQUEST['gid'] ?? 0;
5253         $uid = $user_info['uid'];
5254
5255         // get data of the specified group id or all groups if not specified
5256         if ($gid != 0) {
5257                 $r = q(
5258                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5259                         intval($uid),
5260                         intval($gid)
5261                 );
5262                 // error message if specified gid is not in database
5263                 if (!DBA::isResult($r)) {
5264                         throw new BadRequestException("gid not available");
5265                 }
5266         } else {
5267                 $r = q(
5268                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5269                         intval($uid)
5270                 );
5271         }
5272
5273         // loop through all groups and retrieve all members for adding data in the user array
5274         $grps = [];
5275         foreach ($r as $rr) {
5276                 $members = Contact\Group::getById($rr['id']);
5277                 $users = [];
5278
5279                 if ($type == "xml") {
5280                         $user_element = "users";
5281                         $k = 0;
5282                         foreach ($members as $member) {
5283                                 $user = api_get_user($a, $member['nurl']);
5284                                 $users[$k++.":user"] = $user;
5285                         }
5286                 } else {
5287                         $user_element = "user";
5288                         foreach ($members as $member) {
5289                                 $user = api_get_user($a, $member['nurl']);
5290                                 $users[] = $user;
5291                         }
5292                 }
5293                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5294         }
5295         return api_format_data("groups", $type, ['group' => $grps]);
5296 }
5297 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5298
5299
5300 /**
5301  * Delete the specified group of the user.
5302  *
5303  * @param string $type Return type (atom, rss, xml, json)
5304  *
5305  * @return array|string
5306  * @throws BadRequestException
5307  * @throws ForbiddenException
5308  * @throws ImagickException
5309  * @throws InternalServerErrorException
5310  * @throws UnauthorizedException
5311  */
5312 function api_friendica_group_delete($type)
5313 {
5314         $a = DI::app();
5315
5316         if (api_user() === false) {
5317                 throw new ForbiddenException();
5318         }
5319
5320         // params
5321         $user_info = api_get_user($a);
5322         $gid = $_REQUEST['gid'] ?? 0;
5323         $name = $_REQUEST['name'] ?? '';
5324         $uid = $user_info['uid'];
5325
5326         // error if no gid specified
5327         if ($gid == 0 || $name == "") {
5328                 throw new BadRequestException('gid or name not specified');
5329         }
5330
5331         // get data of the specified group id
5332         $r = q(
5333                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5334                 intval($uid),
5335                 intval($gid)
5336         );
5337         // error message if specified gid is not in database
5338         if (!DBA::isResult($r)) {
5339                 throw new BadRequestException('gid not available');
5340         }
5341
5342         // get data of the specified group id and group name
5343         $rname = q(
5344                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5345                 intval($uid),
5346                 intval($gid),
5347                 DBA::escape($name)
5348         );
5349         // error message if specified gid is not in database
5350         if (!DBA::isResult($rname)) {
5351                 throw new BadRequestException('wrong group name');
5352         }
5353
5354         // delete group
5355         $ret = Group::removeByName($uid, $name);
5356         if ($ret) {
5357                 // return success
5358                 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5359                 return api_format_data("group_delete", $type, ['result' => $success]);
5360         } else {
5361                 throw new BadRequestException('other API error');
5362         }
5363 }
5364 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5365
5366 /**
5367  * Delete a group.
5368  *
5369  * @param string $type Return type (atom, rss, xml, json)
5370  *
5371  * @return array|string
5372  * @throws BadRequestException
5373  * @throws ForbiddenException
5374  * @throws ImagickException
5375  * @throws InternalServerErrorException
5376  * @throws UnauthorizedException
5377  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5378  */
5379 function api_lists_destroy($type)
5380 {
5381         $a = DI::app();
5382
5383         if (api_user() === false) {
5384                 throw new ForbiddenException();
5385         }
5386
5387         // params
5388         $user_info = api_get_user($a);
5389         $gid = $_REQUEST['list_id'] ?? 0;
5390         $uid = $user_info['uid'];
5391
5392         // error if no gid specified
5393         if ($gid == 0) {
5394                 throw new BadRequestException('gid not specified');
5395         }
5396
5397         // get data of the specified group id
5398         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5399         // error message if specified gid is not in database
5400         if (!$group) {
5401                 throw new BadRequestException('gid not available');
5402         }
5403
5404         if (Group::remove($gid)) {
5405                 $list = [
5406                         'name' => $group['name'],
5407                         'id' => intval($gid),
5408                         'id_str' => (string) $gid,
5409                         'user' => $user_info
5410                 ];
5411
5412                 return api_format_data("lists", $type, ['lists' => $list]);
5413         }
5414 }
5415 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5416
5417 /**
5418  * Add a new group to the database.
5419  *
5420  * @param  string $name  Group name
5421  * @param  int    $uid   User ID
5422  * @param  array  $users List of users to add to the group
5423  *
5424  * @return array
5425  * @throws BadRequestException
5426  */
5427 function group_create($name, $uid, $users = [])
5428 {
5429         // error if no name specified
5430         if ($name == "") {
5431                 throw new BadRequestException('group name not specified');
5432         }
5433
5434         // get data of the specified group name
5435         $rname = q(
5436                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5437                 intval($uid),
5438                 DBA::escape($name)
5439         );
5440         // error message if specified group name already exists
5441         if (DBA::isResult($rname)) {
5442                 throw new BadRequestException('group name already exists');
5443         }
5444
5445         // check if specified group name is a deleted group
5446         $rname = q(
5447                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5448                 intval($uid),
5449                 DBA::escape($name)
5450         );
5451         // error message if specified group name already exists
5452         if (DBA::isResult($rname)) {
5453                 $reactivate_group = true;
5454         }
5455
5456         // create group
5457         $ret = Group::create($uid, $name);
5458         if ($ret) {
5459                 $gid = Group::getIdByName($uid, $name);
5460         } else {
5461                 throw new BadRequestException('other API error');
5462         }
5463
5464         // add members
5465         $erroraddinguser = false;
5466         $errorusers = [];
5467         foreach ($users as $user) {
5468                 $cid = $user['cid'];
5469                 // check if user really exists as contact
5470                 $contact = q(
5471                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5472                         intval($cid),
5473                         intval($uid)
5474                 );
5475                 if (count($contact)) {
5476                         Group::addMember($gid, $cid);
5477                 } else {
5478                         $erroraddinguser = true;
5479                         $errorusers[] = $cid;
5480                 }
5481         }
5482
5483         // return success message incl. missing users in array
5484         $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5485
5486         return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5487 }
5488
5489 /**
5490  * Create the specified group with the posted array of contacts.
5491  *
5492  * @param string $type Return type (atom, rss, xml, json)
5493  *
5494  * @return array|string
5495  * @throws BadRequestException
5496  * @throws ForbiddenException
5497  * @throws ImagickException
5498  * @throws InternalServerErrorException
5499  * @throws UnauthorizedException
5500  */
5501 function api_friendica_group_create($type)
5502 {
5503         $a = DI::app();
5504
5505         if (api_user() === false) {
5506                 throw new ForbiddenException();
5507         }
5508
5509         // params
5510         $user_info = api_get_user($a);
5511         $name = $_REQUEST['name'] ?? '';
5512         $uid = $user_info['uid'];
5513         $json = json_decode($_POST['json'], true);
5514         $users = $json['user'];
5515
5516         $success = group_create($name, $uid, $users);
5517
5518         return api_format_data("group_create", $type, ['result' => $success]);
5519 }
5520 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5521
5522 /**
5523  * Create a new group.
5524  *
5525  * @param string $type Return type (atom, rss, xml, json)
5526  *
5527  * @return array|string
5528  * @throws BadRequestException
5529  * @throws ForbiddenException
5530  * @throws ImagickException
5531  * @throws InternalServerErrorException
5532  * @throws UnauthorizedException
5533  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5534  */
5535 function api_lists_create($type)
5536 {
5537         $a = DI::app();
5538
5539         if (api_user() === false) {
5540                 throw new ForbiddenException();
5541         }
5542
5543         // params
5544         $user_info = api_get_user($a);
5545         $name = $_REQUEST['name'] ?? '';
5546         $uid = $user_info['uid'];
5547
5548         $success = group_create($name, $uid);
5549         if ($success['success']) {
5550                 $grp = [
5551                         'name' => $success['name'],
5552                         'id' => intval($success['gid']),
5553                         'id_str' => (string) $success['gid'],
5554                         'user' => $user_info
5555                 ];
5556
5557                 return api_format_data("lists", $type, ['lists'=>$grp]);
5558         }
5559 }
5560 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5561
5562 /**
5563  * Update the specified group with the posted array of contacts.
5564  *
5565  * @param string $type Return type (atom, rss, xml, json)
5566  *
5567  * @return array|string
5568  * @throws BadRequestException
5569  * @throws ForbiddenException
5570  * @throws ImagickException
5571  * @throws InternalServerErrorException
5572  * @throws UnauthorizedException
5573  */
5574 function api_friendica_group_update($type)
5575 {
5576         $a = DI::app();
5577
5578         if (api_user() === false) {
5579                 throw new ForbiddenException();
5580         }
5581
5582         // params
5583         $user_info = api_get_user($a);
5584         $uid = $user_info['uid'];
5585         $gid = $_REQUEST['gid'] ?? 0;
5586         $name = $_REQUEST['name'] ?? '';
5587         $json = json_decode($_POST['json'], true);
5588         $users = $json['user'];
5589
5590         // error if no name specified
5591         if ($name == "") {
5592                 throw new BadRequestException('group name not specified');
5593         }
5594
5595         // error if no gid specified
5596         if ($gid == "") {
5597                 throw new BadRequestException('gid not specified');
5598         }
5599
5600         // remove members
5601         $members = Contact\Group::getById($gid);
5602         foreach ($members as $member) {
5603                 $cid = $member['id'];
5604                 foreach ($users as $user) {
5605                         $found = ($user['cid'] == $cid ? true : false);
5606                 }
5607                 if (!isset($found) || !$found) {
5608                         Group::removeMemberByName($uid, $name, $cid);
5609                 }
5610         }
5611
5612         // add members
5613         $erroraddinguser = false;
5614         $errorusers = [];
5615         foreach ($users as $user) {
5616                 $cid = $user['cid'];
5617                 // check if user really exists as contact
5618                 $contact = q(
5619                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5620                         intval($cid),
5621                         intval($uid)
5622                 );
5623
5624                 if (count($contact)) {
5625                         Group::addMember($gid, $cid);
5626                 } else {
5627                         $erroraddinguser = true;
5628                         $errorusers[] = $cid;
5629                 }
5630         }
5631
5632         // return success message incl. missing users in array
5633         $status = ($erroraddinguser ? "missing user" : "ok");
5634         $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5635         return api_format_data("group_update", $type, ['result' => $success]);
5636 }
5637
5638 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5639
5640 /**
5641  * Update information about a group.
5642  *
5643  * @param string $type Return type (atom, rss, xml, json)
5644  *
5645  * @return array|string
5646  * @throws BadRequestException
5647  * @throws ForbiddenException
5648  * @throws ImagickException
5649  * @throws InternalServerErrorException
5650  * @throws UnauthorizedException
5651  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5652  */
5653 function api_lists_update($type)
5654 {
5655         $a = DI::app();
5656
5657         if (api_user() === false) {
5658                 throw new ForbiddenException();
5659         }
5660
5661         // params
5662         $user_info = api_get_user($a);
5663         $gid = $_REQUEST['list_id'] ?? 0;
5664         $name = $_REQUEST['name'] ?? '';
5665         $uid = $user_info['uid'];
5666
5667         // error if no gid specified
5668         if ($gid == 0) {
5669                 throw new BadRequestException('gid not specified');
5670         }
5671
5672         // get data of the specified group id
5673         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5674         // error message if specified gid is not in database
5675         if (!$group) {
5676                 throw new BadRequestException('gid not available');
5677         }
5678
5679         if (Group::update($gid, $name)) {
5680                 $list = [
5681                         'name' => $name,
5682                         'id' => intval($gid),
5683                         'id_str' => (string) $gid,
5684                         'user' => $user_info
5685                 ];
5686
5687                 return api_format_data("lists", $type, ['lists' => $list]);
5688         }
5689 }
5690
5691 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5692
5693 /**
5694  *
5695  * @param string $type Return type (atom, rss, xml, json)
5696  *
5697  * @return array|string
5698  * @throws BadRequestException
5699  * @throws ForbiddenException
5700  * @throws ImagickException
5701  * @throws InternalServerErrorException
5702  */
5703 function api_friendica_activity($type)
5704 {
5705         $a = DI::app();
5706
5707         if (api_user() === false) {
5708                 throw new ForbiddenException();
5709         }
5710         $verb = strtolower($a->argv[3]);
5711         $verb = preg_replace("|\..*$|", "", $verb);
5712
5713         $id = $_REQUEST['id'] ?? 0;
5714
5715         $res = Item::performActivity($id, $verb, api_user());
5716
5717         if ($res) {
5718                 if ($type == "xml") {
5719                         $ok = "true";
5720                 } else {
5721                         $ok = "ok";
5722                 }
5723                 return api_format_data('ok', $type, ['ok' => $ok]);
5724         } else {
5725                 throw new BadRequestException('Error adding activity');
5726         }
5727 }
5728
5729 /// @TODO move to top of file or somewhere better
5730 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5731 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5732 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5733 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5734 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5735 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5736 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5737 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5738 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5739 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5740
5741 /**
5742  * Returns notifications
5743  *
5744  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5745  *
5746  * @return string|array
5747  * @throws ForbiddenException
5748  * @throws BadRequestException
5749  * @throws Exception
5750  */
5751 function api_friendica_notification($type)
5752 {
5753         $a = DI::app();
5754
5755         if (api_user() === false) {
5756                 throw new ForbiddenException();
5757         }
5758         if ($a->argc!==3) {
5759                 throw new BadRequestException("Invalid argument count");
5760         }
5761
5762         $notifications = DI::notification()->getApiList(local_user());
5763
5764         if ($type == "xml") {
5765                 $xmlnotes = false;
5766                 if (!empty($notifications)) {
5767                         foreach ($notifications as $notification) {
5768                                 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5769                         }
5770                 }
5771
5772                 $result = $xmlnotes;
5773         } elseif (count($notifications) > 0) {
5774                 $result = $notifications->getArrayCopy();
5775         } else {
5776                 $result = false;
5777         }
5778
5779         return api_format_data("notes", $type, ['note' => $result]);
5780 }
5781
5782 /**
5783  * Set notification as seen and returns associated item (if possible)
5784  *
5785  * POST request with 'id' param as notification id
5786  *
5787  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5788  * @return string|array
5789  * @throws BadRequestException
5790  * @throws ForbiddenException
5791  * @throws ImagickException
5792  * @throws InternalServerErrorException
5793  * @throws UnauthorizedException
5794  */
5795 function api_friendica_notification_seen($type)
5796 {
5797         $a         = DI::app();
5798         $user_info = api_get_user($a);
5799
5800         if (api_user() === false || $user_info === false) {
5801                 throw new ForbiddenException();
5802         }
5803         if ($a->argc !== 4) {
5804                 throw new BadRequestException("Invalid argument count");
5805         }
5806
5807         $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5808
5809         try {
5810                 $notify = DI::notify()->getByID($id, api_user());
5811                 DI::notify()->setSeen(true, $notify);
5812
5813                 if ($notify->otype === Notification\ObjectType::ITEM) {
5814                         $item = Post::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5815                         if (DBA::isResult($item)) {
5816                                 // we found the item, return it to the user
5817                                 $ret  = api_format_items([$item], $user_info, false, $type);
5818                                 $data = ['status' => $ret];
5819                                 return api_format_data("status", $type, $data);
5820                         }
5821                         // the item can't be found, but we set the notification as seen, so we count this as a success
5822                 }
5823                 return api_format_data('result', $type, ['result' => "success"]);
5824         } catch (NotFoundException $e) {
5825                 throw new BadRequestException('Invalid argument', $e);
5826         } catch (Exception $e) {
5827                 throw new InternalServerErrorException('Internal Server exception', $e);
5828         }
5829 }
5830
5831 /// @TODO move to top of file or somewhere better
5832 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5833 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5834
5835 /**
5836  * update a direct_message to seen state
5837  *
5838  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5839  * @return string|array (success result=ok, error result=error with error message)
5840  * @throws BadRequestException
5841  * @throws ForbiddenException
5842  * @throws ImagickException
5843  * @throws InternalServerErrorException
5844  * @throws UnauthorizedException
5845  */
5846 function api_friendica_direct_messages_setseen($type)
5847 {
5848         $a = DI::app();
5849         if (api_user() === false) {
5850                 throw new ForbiddenException();
5851         }
5852
5853         // params
5854         $user_info = api_get_user($a);
5855         $uid = $user_info['uid'];
5856         $id = $_REQUEST['id'] ?? 0;
5857
5858         // return error if id is zero
5859         if ($id == "") {
5860                 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5861                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5862         }
5863
5864         // error message if specified id is not in database
5865         if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5866                 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5867                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5868         }
5869
5870         // update seen indicator
5871         $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5872
5873         if ($result) {
5874                 // return success
5875                 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5876                 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5877         } else {
5878                 $answer = ['result' => 'error', 'message' => 'unknown error'];
5879                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5880         }
5881 }
5882
5883 /// @TODO move to top of file or somewhere better
5884 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5885
5886 /**
5887  * search for direct_messages containing a searchstring through api
5888  *
5889  * @param string $type      Known types are 'atom', 'rss', 'xml' and 'json'
5890  * @param string $box
5891  * @return string|array (success: success=true if found and search_result contains found messages,
5892  *                          success=false if nothing was found, search_result='nothing found',
5893  *                          error: result=error with error message)
5894  * @throws BadRequestException
5895  * @throws ForbiddenException
5896  * @throws ImagickException
5897  * @throws InternalServerErrorException
5898  * @throws UnauthorizedException
5899  */
5900 function api_friendica_direct_messages_search($type, $box = "")
5901 {
5902         $a = DI::app();
5903
5904         if (api_user() === false) {
5905                 throw new ForbiddenException();
5906         }
5907
5908         // params
5909         $user_info = api_get_user($a);
5910         $searchstring = $_REQUEST['searchstring'] ?? '';
5911         $uid = $user_info['uid'];
5912
5913         // error if no searchstring specified
5914         if ($searchstring == "") {
5915                 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5916                 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5917         }
5918
5919         // get data for the specified searchstring
5920         $r = q(
5921                 "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",
5922                 intval($uid),
5923                 DBA::escape('%'.$searchstring.'%')
5924         );
5925
5926         $profile_url = $user_info["url"];
5927
5928         // message if nothing was found
5929         if (!DBA::isResult($r)) {
5930                 $success = ['success' => false, 'search_results' => 'problem with query'];
5931         } elseif (count($r) == 0) {
5932                 $success = ['success' => false, 'search_results' => 'nothing found'];
5933         } else {
5934                 $ret = [];
5935                 foreach ($r as $item) {
5936                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
5937                                 $recipient = $user_info;
5938                                 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5939                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5940                                 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5941                                 $sender = $user_info;
5942                         }
5943
5944                         if (isset($recipient) && isset($sender)) {
5945                                 $ret[] = api_format_messages($item, $recipient, $sender);
5946                         }
5947                 }
5948                 $success = ['success' => true, 'search_results' => $ret];
5949         }
5950
5951         return api_format_data("direct_message_search", $type, ['$result' => $success]);
5952 }
5953
5954 /// @TODO move to top of file or somewhere better
5955 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5956
5957 /**
5958  * Returns a list of saved searches.
5959  *
5960  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5961  *
5962  * @param  string $type Return format: json or xml
5963  *
5964  * @return string|array
5965  * @throws Exception
5966  */
5967 function api_saved_searches_list($type)
5968 {
5969         $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5970
5971         $result = [];
5972         while ($term = DBA::fetch($terms)) {
5973                 $result[] = [
5974                         'created_at' => api_date(time()),
5975                         'id' => intval($term['id']),
5976                         'id_str' => $term['id'],
5977                         'name' => $term['term'],
5978                         'position' => null,
5979                         'query' => $term['term']
5980                 ];
5981         }
5982
5983         DBA::close($terms);
5984
5985         return api_format_data("terms", $type, ['terms' => $result]);
5986 }
5987
5988 /// @TODO move to top of file or somewhere better
5989 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5990
5991 /*
5992  * Number of comments
5993  *
5994  * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
5995  *
5996  * @param object $data [Status, Status]
5997  *
5998  * @return void
5999  */
6000 function bindComments(&$data) 
6001 {
6002         if (count($data) == 0) {
6003                 return;
6004         }
6005         
6006         $ids = [];
6007         $comments = [];
6008         foreach ($data as $item) {
6009                 $ids[] = $item['id'];
6010         }
6011
6012         $idStr = DBA::escape(implode(', ', $ids));
6013         $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6014         $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6015         $itemsData = DBA::toArray($items);
6016
6017         foreach ($itemsData as $item) {
6018                 $comments[$item['parent']] = $item['comments'];
6019         }
6020
6021         foreach ($data as $idx => $item) {
6022                 $id = $item['id'];
6023                 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6024         }
6025 }
6026
6027 /*
6028 @TODO Maybe open to implement?
6029 To.Do:
6030         [pagename] => api/1.1/statuses/lookup.json
6031         [id] => 605138389168451584
6032         [include_cards] => true
6033         [cards_platform] => Android-12
6034         [include_entities] => true
6035         [include_my_retweet] => 1
6036         [include_rts] => 1
6037         [include_reply_count] => true
6038         [include_descendent_reply_count] => true
6039 (?)
6040
6041
6042 Not implemented by now:
6043 statuses/retweets_of_me
6044 friendships/create
6045 friendships/destroy
6046 friendships/exists
6047 friendships/show
6048 account/update_location
6049 account/update_profile_background_image
6050 blocks/create
6051 blocks/destroy
6052 friendica/profile/update
6053 friendica/profile/create
6054 friendica/profile/delete
6055
6056 Not implemented in status.net:
6057 statuses/retweeted_to_me
6058 statuses/retweeted_by_me
6059 direct_messages/destroy
6060 account/end_session
6061 account/update_delivery_device
6062 notifications/follow
6063 notifications/leave
6064 blocks/exists
6065 blocks/blocking
6066 lists
6067 */