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