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