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