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