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