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