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