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