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