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