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