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