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