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