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