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