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