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