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