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