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