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