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