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