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