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