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