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