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