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