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