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