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