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