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