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