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