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