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