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