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