]> git.mxchange.org Git - friendica.git/blob - include/api.php
cea356602e6afc3e7eed0d4eff24e9b09555ee12
[friendica.git] / include / api.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
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\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Core\System;
33 use Friendica\Database\DBA;
34 use Friendica\DI;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Group;
37 use Friendica\Model\Item;
38 use Friendica\Model\Mail;
39 use Friendica\Model\Notification;
40 use Friendica\Model\Photo;
41 use Friendica\Model\Post;
42 use Friendica\Model\Profile;
43 use Friendica\Model\User;
44 use Friendica\Model\Verb;
45 use Friendica\Module\BaseApi;
46 use Friendica\Network\HTTPException;
47 use Friendica\Network\HTTPException\BadRequestException;
48 use Friendica\Network\HTTPException\ForbiddenException;
49 use Friendica\Network\HTTPException\InternalServerErrorException;
50 use Friendica\Network\HTTPException\MethodNotAllowedException;
51 use Friendica\Network\HTTPException\NotFoundException;
52 use Friendica\Network\HTTPException\TooManyRequestsException;
53 use Friendica\Network\HTTPException\UnauthorizedException;
54 use Friendica\Object\Image;
55 use Friendica\Protocol\Activity;
56 use Friendica\Security\BasicAuth;
57 use Friendica\Security\OAuth;
58 use Friendica\Util\DateTimeFormat;
59 use Friendica\Util\Images;
60 use Friendica\Util\Network;
61 use Friendica\Util\Strings;
62
63 require_once __DIR__ . '/../mod/item.php';
64 require_once __DIR__ . '/../mod/wall_upload.php';
65
66 define('API_METHOD_ANY', '*');
67 define('API_METHOD_GET', 'GET');
68 define('API_METHOD_POST', 'POST,PUT');
69 define('API_METHOD_DELETE', 'POST,DELETE');
70
71 define('API_LOG_PREFIX', 'API {action} - ');
72
73 $API = [];
74 $called_api = [];
75
76 /**
77  * Auth API user
78  *
79  * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
80  * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
81  * into a page, and visitors will post something without noticing it).
82  */
83 function api_user()
84 {
85         $user = OAuth::getCurrentUserID();
86         if (!empty($user)) {
87                 return $user;
88         }
89
90         if (!empty($_SESSION['allow_api'])) {
91                 return local_user();
92         }
93
94         return false;
95 }
96
97 /**
98  * Get source name from API client
99  *
100  * Clients can send 'source' parameter to be show in post metadata
101  * as "sent via <source>".
102  * Some clients doesn't send a source param, we support ones we know
103  * (only Twidere, atm)
104  *
105  * @return string
106  *        Client source name, default to "api" if unset/unknown
107  * @throws Exception
108  */
109 function api_source()
110 {
111         if (requestdata('source')) {
112                 return requestdata('source');
113         }
114
115         // Support for known clients that doesn't send a source name
116         if (!empty($_SERVER['HTTP_USER_AGENT'])) {
117                 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
118                         return "Twidere";
119                 }
120
121                 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
122         } else {
123                 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
124         }
125
126         return "api";
127 }
128
129 /**
130  * Format date for API
131  *
132  * @param string $str Source date, as UTC
133  * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
134  * @throws Exception
135  */
136 function api_date($str)
137 {
138         // Wed May 23 06:01:13 +0000 2007
139         return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
140 }
141
142 /**
143  * Register a function to be the endpoint for defined API path.
144  *
145  * @param string $path   API URL path, relative to DI::baseUrl()
146  * @param string $func   Function name to call on path request
147  * @param bool   $auth   API need logged user
148  * @param string $method HTTP method reqiured to call this endpoint.
149  *                       One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
150  *                       Default to API_METHOD_ANY
151  */
152 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
153 {
154         global $API;
155
156         $API[$path] = [
157                 'func'   => $func,
158                 'auth'   => $auth,
159                 'method' => $method,
160         ];
161
162         // Workaround for hotot
163         $path = str_replace("api/", "api/1.1/", $path);
164
165         $API[$path] = [
166                 'func'   => $func,
167                 'auth'   => $auth,
168                 'method' => $method,
169         ];
170 }
171
172 /**
173  * Check HTTP method of called API
174  *
175  * API endpoints can define which HTTP method to accept when called.
176  * This function check the current HTTP method agains endpoint
177  * registered method.
178  *
179  * @param string $method Required methods, uppercase, separated by comma
180  * @return bool
181  */
182 function api_check_method($method)
183 {
184         if ($method == "*") {
185                 return true;
186         }
187         return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
188 }
189
190 /**
191  * Main API entry point
192  *
193  * Authenticate user, call registered API function, set HTTP headers
194  *
195  * @param App $a App
196  * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
197  * @return string|array API call result
198  * @throws Exception
199  */
200 function api_call(App $a, App\Arguments $args = null)
201 {
202         global $API, $called_api;
203
204         if ($args == null) {
205                 $args = DI::args();
206         }
207
208         $type = "json";
209         if (strpos($args->getCommand(), ".xml") > 0) {
210                 $type = "xml";
211         }
212         if (strpos($args->getCommand(), ".json") > 0) {
213                 $type = "json";
214         }
215         if (strpos($args->getCommand(), ".rss") > 0) {
216                 $type = "rss";
217         }
218         if (strpos($args->getCommand(), ".atom") > 0) {
219                 $type = "atom";
220         }
221
222         try {
223                 foreach ($API as $p => $info) {
224                         if (strpos($args->getCommand(), $p) === 0) {
225                                 if (!api_check_method($info['method'])) {
226                                         throw new MethodNotAllowedException();
227                                 }
228
229                                 $called_api = explode("/", $p);
230
231                                 if (!empty($info['auth']) && BaseApi::getCurrentUserID() === false) {
232                                         BasicAuth::getCurrentUserID(true);
233                                         Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
234                                 }
235
236                                 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
237
238                                 $stamp =  microtime(true);
239                                 $return = call_user_func($info['func'], $type);
240                                 $duration = floatval(microtime(true) - $stamp);
241
242                                 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
243
244                                 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
245
246                                 if (false === $return) {
247                                         /*
248                                                 * api function returned false withour throw an
249                                                 * exception. This should not happend, throw a 500
250                                                 */
251                                         throw new InternalServerErrorException();
252                                 }
253
254                                 switch ($type) {
255                                         case "xml":
256                                                 header("Content-Type: text/xml");
257                                                 break;
258                                         case "json":
259                                                 header("Content-Type: application/json");
260                                                 if (!empty($return)) {
261                                                         $json = json_encode(end($return));
262                                                         if (!empty($_GET['callback'])) {
263                                                                 $json = $_GET['callback'] . "(" . $json . ")";
264                                                         }
265                                                         $return = $json;
266                                                 }
267                                                 break;
268                                         case "rss":
269                                                 header("Content-Type: application/rss+xml");
270                                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
271                                                 break;
272                                         case "atom":
273                                                 header("Content-Type: application/atom+xml");
274                                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
275                                                 break;
276                                 }
277                                 return $return;
278                         }
279                 }
280
281                 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
282                 throw new NotFoundException();
283         } catch (HTTPException $e) {
284                 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
285         }
286 }
287
288 /**
289  * Set values for RSS template
290  *
291  * @param array $arr       Array to be passed to template
292  * @param array $user_info User info
293  * @return array
294  * @throws BadRequestException
295  * @throws ImagickException
296  * @throws InternalServerErrorException
297  * @throws UnauthorizedException
298  * @todo  find proper type-hints
299  */
300 function api_rss_extra($arr, $user_info)
301 {
302         if (is_null($user_info)) {
303                 $uid = BaseApi::getCurrentUserID();
304                 if (empty($uid)) {
305                         throw new ForbiddenException();
306                 }
307
308                 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
309         }
310
311         $arr['$user'] = $user_info;
312         $arr['$rss'] = [
313                 'alternate'    => $user_info['url'],
314                 'self'         => DI::baseUrl() . "/" . DI::args()->getQueryString(),
315                 'base'         => DI::baseUrl(),
316                 'updated'      => api_date(null),
317                 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
318                 'language'     => $user_info['lang'],
319                 'logo'         => DI::baseUrl() . "/images/friendica-32.png",
320         ];
321
322         return $arr;
323 }
324
325
326 /**
327  * Unique contact to contact url.
328  *
329  * @param int $id Contact id
330  * @return bool|string
331  *                Contact url or False if contact id is unknown
332  * @throws Exception
333  */
334 function api_unique_id_to_nurl($id)
335 {
336         $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
337
338         if (DBA::isResult($r)) {
339                 return $r["nurl"];
340         } else {
341                 return false;
342         }
343 }
344
345 /**
346  * Get user info array.
347  *
348  * @param App        $a          App
349  * @param int|string $contact_id Contact ID or URL
350  * @return array|bool
351  * @throws BadRequestException
352  * @throws ImagickException
353  * @throws InternalServerErrorException
354  * @throws UnauthorizedException
355  */
356 function api_get_user($contact_id = null)
357 {
358         global $called_api;
359
360         $user = null;
361         $extra_query = "";
362         $url = "";
363
364         Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
365
366         // Searching for contact URL
367         if (!is_null($contact_id) && (intval($contact_id) == 0)) {
368                 $user = Strings::normaliseLink($contact_id);
369                 $url = $user;
370                 $extra_query = "AND `contact`.`nurl` = ? ";
371                 if (BaseApi::getCurrentUserID() !== false) {
372                         $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
373                 }
374         }
375
376         // Searching for contact id with uid = 0
377         if (!is_null($contact_id) && (intval($contact_id) != 0)) {
378                 $user = api_unique_id_to_nurl(intval($contact_id));
379
380                 if ($user == "") {
381                         throw new BadRequestException("User ID ".$contact_id." not found.");
382                 }
383
384                 $url = $user;
385                 $extra_query = "AND `contact`.`nurl` = ? ";
386                 if (BaseApi::getCurrentUserID() !== false) {
387                         $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
388                 }
389         }
390
391         if (is_null($user) && !empty($_GET['user_id'])) {
392                 $user = api_unique_id_to_nurl($_GET['user_id']);
393
394                 if ($user == "") {
395                         throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
396                 }
397
398                 $url = $user;
399                 $extra_query = "AND `contact`.`nurl` = ? ";
400                 if (BaseApi::getCurrentUserID() !== false) {
401                         $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
402                 }
403         }
404         if (is_null($user) && !empty($_GET['screen_name'])) {
405                 $user = $_GET['screen_name'];
406                 $extra_query = "AND `contact`.`nick` = ? ";
407                 if (BaseApi::getCurrentUserID() !== false) {
408                         $extra_query .= "AND `contact`.`uid`=".intval(BaseApi::getCurrentUserID());
409                 }
410         }
411
412         if (is_null($user) && !empty($_GET['profileurl'])) {
413                 $user = Strings::normaliseLink($_GET['profileurl']);
414                 $extra_query = "AND `contact`.`nurl` = ? ";
415                 if (BaseApi::getCurrentUserID() !== false) {
416                         $extra_query .= "AND `contact`.`uid`=".intval(BaseApi::getCurrentUserID());
417                 }
418         }
419
420         // $called_api is the API path exploded on / and is expected to have at least 2 elements
421         if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) {
422                 $argid = count($called_api);
423                 if (!empty(DI::args()->getArgv()[$argid])) {
424                         $data = explode(".", DI::args()->getArgv()[$argid]);
425                         if (count($data) > 1) {
426                                 [$user, $null] = $data;
427                         }
428                 }
429                 if (is_numeric($user)) {
430                         $user = api_unique_id_to_nurl(intval($user));
431
432                         if ($user != "") {
433                                 $url = $user;
434                                 $extra_query = "AND `contact`.`nurl` = ? ";
435                                 if (BaseApi::getCurrentUserID() !== false) {
436                                         $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
437                                 }
438                         }
439                 } else {
440                         $extra_query = "AND `contact`.`nick` = ? ";
441                         if (BaseApi::getCurrentUserID() !== false) {
442                                 $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
443                         }
444                 }
445         }
446
447         Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
448
449         if (!$user) {
450                 if (BaseApi::getCurrentUserID() === false) {
451                         BasicAuth::getCurrentUserID(true);
452                         return false;
453                 } else {
454                         $user = BaseApi::getCurrentUserID();
455                         $extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
456                 }
457         }
458
459         Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
460
461         // user info
462         $uinfo = DBA::toArray(DBA::p(
463                 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
464                         WHERE 1
465                 $extra_query",
466                 $user
467         ));
468
469         if (DBA::isResult($uinfo)) {
470                 // Selecting the id by priority, friendica first
471                 api_best_nickname($uinfo);
472                 return DI::twitterUser()->createFromContactId($uinfo[0]['cid'], $uinfo[0]['uid'])->toArray();
473         }
474
475         if ($url == "") {
476                 throw new BadRequestException("User not found.");
477         }
478
479         $cid = Contact::getIdForURL($url, 0, false);
480
481         if (!empty($cid)) {
482                 return DI::twitterUser()->createFromContactId($cid, 0)->toArray();
483         } else {
484                 throw new BadRequestException("User ".$url." not found.");
485         }
486 }
487
488 /**
489  * return api-formatted array for item's author and owner
490  *
491  * @param App   $a    App
492  * @param array $item item from db
493  * @return array(array:author, array:owner)
494  * @throws BadRequestException
495  * @throws ImagickException
496  * @throws InternalServerErrorException
497  * @throws UnauthorizedException
498  */
499 function api_item_get_user(App $a, $item)
500 {
501         $status_user = DI::twitterUser()->createFromContactId($item['author-id'] ?? 0, BaseApi::getCurrentUserID())->toArray();
502
503         $author_user = $status_user;
504
505         $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
506
507         if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
508                 $owner_user = DI::twitterUser()->createFromContactId($item['owner-id'] ?? 0, BaseApi::getCurrentUserID())->toArray();
509         } else {
510                 $owner_user = $author_user;
511         }
512
513         return ([$status_user, $author_user, $owner_user]);
514 }
515
516 /**
517  * TWITTER API
518  */
519
520 /**
521  * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
522  * returns a 401 status code and an error message if not.
523  *
524  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
525  *
526  * @param string $type Return type (atom, rss, xml, json)
527  * @return array|string
528  * @throws BadRequestException
529  * @throws ForbiddenException
530  * @throws ImagickException
531  * @throws InternalServerErrorException
532  * @throws UnauthorizedException
533  */
534 function api_account_verify_credentials($type)
535 {
536         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
537
538         unset($_REQUEST["user_id"]);
539         unset($_GET["user_id"]);
540
541         unset($_REQUEST["screen_name"]);
542         unset($_GET["screen_name"]);
543
544         $skip_status = $_REQUEST['skip_status'] ?? false;
545
546         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
547
548         // "verified" isn't used here in the standard
549         unset($user_info["verified"]);
550
551         // - Adding last status
552         if (!$skip_status) {
553                 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
554                 if (!empty($item)) {
555                         $user_info['status'] = api_format_item($item, $type);
556                 }
557         }
558
559         // "uid" and "self" are only needed for some internal stuff, so remove it from here
560         unset($user_info["uid"]);
561         unset($user_info["self"]);
562
563         return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
564 }
565
566 /// @TODO move to top of file or somewhere better
567 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
568
569 /**
570  * Get data from $_POST or $_GET
571  *
572  * @param string $k
573  * @return null
574  */
575 function requestdata($k)
576 {
577         if (!empty($_POST[$k])) {
578                 return $_POST[$k];
579         }
580         if (!empty($_GET[$k])) {
581                 return $_GET[$k];
582         }
583         return null;
584 }
585
586 /**
587  * Deprecated function to upload media.
588  *
589  * @param string $type Return type (atom, rss, xml, json)
590  *
591  * @return array|string
592  * @throws BadRequestException
593  * @throws ForbiddenException
594  * @throws ImagickException
595  * @throws InternalServerErrorException
596  * @throws UnauthorizedException
597  */
598 function api_statuses_mediap($type)
599 {
600         $a = DI::app();
601
602         if (empty(BaseApi::getCurrentUserID())) {
603                 throw new ForbiddenException();
604         }
605
606         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
607
608         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
609
610         $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
611         $_REQUEST['api_source'] = true;
612         $txt = requestdata('status') ?? '';
613         /// @TODO old-lost code?
614         //$txt = urldecode(requestdata('status'));
615
616         if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
617                 $txt = HTML::toBBCodeVideo($txt);
618                 $config = HTMLPurifier_Config::createDefault();
619                 $config->set('Cache.DefinitionImpl', null);
620                 $purifier = new HTMLPurifier($config);
621                 $txt = $purifier->purify($txt);
622         }
623         $txt = HTML::toBBCode($txt);
624
625         DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
626
627         $picture = wall_upload_post($a, false);
628
629         // now that we have the img url in bbcode we can add it to the status and insert the wall item.
630         $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
631         $item_id = item_post($a);
632
633         // output the post that we just posted.
634         return api_status_show($type, $item_id);
635 }
636
637 /// @TODO move this to top of file or somewhere better!
638 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
639
640 /**
641  * Updates the user’s current status.
642  *
643  * @param string $type Return type (atom, rss, xml, json)
644  *
645  * @return array|string
646  * @throws BadRequestException
647  * @throws ForbiddenException
648  * @throws ImagickException
649  * @throws InternalServerErrorException
650  * @throws TooManyRequestsException
651  * @throws UnauthorizedException
652  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
653  */
654 function api_statuses_update($type)
655 {
656         $a = DI::app();
657
658         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
659
660         // convert $_POST array items to the form we use for web posts.
661         if (requestdata('htmlstatus')) {
662                 $txt = requestdata('htmlstatus') ?? '';
663                 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
664                         $txt = HTML::toBBCodeVideo($txt);
665
666                         $config = HTMLPurifier_Config::createDefault();
667                         $config->set('Cache.DefinitionImpl', null);
668
669                         $purifier = new HTMLPurifier($config);
670                         $txt = $purifier->purify($txt);
671
672                         $_REQUEST['body'] = HTML::toBBCode($txt);
673                 }
674         } else {
675                 $_REQUEST['body'] = requestdata('status');
676         }
677
678         $_REQUEST['title'] = requestdata('title');
679
680         $parent = requestdata('in_reply_to_status_id');
681
682         // Twidere sends "-1" if it is no reply ...
683         if ($parent == -1) {
684                 $parent = "";
685         }
686
687         if (ctype_digit($parent)) {
688                 $_REQUEST['parent'] = $parent;
689         } else {
690                 $_REQUEST['parent_uri'] = $parent;
691         }
692
693         if (requestdata('lat') && requestdata('long')) {
694                 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
695         }
696         $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
697
698         if (!$parent) {
699                 // Check for throttling (maximum posts per day, week and month)
700                 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
701                 if ($throttle_day > 0) {
702                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
703
704                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
705                         $posts_day = Post::count($condition);
706
707                         if ($posts_day > $throttle_day) {
708                                 logger::info('Daily posting limit reached for user '.BaseApi::getCurrentUserID());
709                                 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
710                                 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));
711                         }
712                 }
713
714                 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
715                 if ($throttle_week > 0) {
716                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
717
718                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
719                         $posts_week = Post::count($condition);
720
721                         if ($posts_week > $throttle_week) {
722                                 logger::info('Weekly posting limit reached for user '.BaseApi::getCurrentUserID());
723                                 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
724                                 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));
725                         }
726                 }
727
728                 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
729                 if ($throttle_month > 0) {
730                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
731
732                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
733                         $posts_month = Post::count($condition);
734
735                         if ($posts_month > $throttle_month) {
736                                 logger::info('Monthly posting limit reached for user '.BaseApi::getCurrentUserID());
737                                 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
738                                 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));
739                         }
740                 }
741         }
742
743         if (requestdata('media_ids')) {
744                 $ids = explode(',', requestdata('media_ids') ?? '');
745         } elseif (!empty($_FILES['media'])) {
746                 // upload the image if we have one
747                 $picture = wall_upload_post($a, false);
748                 if (is_array($picture)) {
749                         $ids[] = $picture['id'];
750                 }
751         }
752
753         $attachments = [];
754         $ressources = [];
755
756         if (!empty($ids)) {
757                 foreach ($ids as $id) {
758                         $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
759                                         INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
760                                                 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
761                                         ORDER BY `photo`.`width` DESC LIMIT 2", $id, BaseApi::getCurrentUserID()));
762
763                         if (!empty($media)) {
764                                 $ressources[] = $media[0]['resource-id'];
765                                 $phototypes = Images::supportedTypes();
766                                 $ext = $phototypes[$media[0]['type']];
767
768                                 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
769                                         'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
770                                         'size' => $media[0]['datasize'],
771                                         'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
772                                         'description' => $media[0]['desc'] ?? '',
773                                         'width' => $media[0]['width'],
774                                         'height' => $media[0]['height']];
775
776                                 if (count($media) > 1) {
777                                         $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
778                                         $attachment['preview-width'] = $media[1]['width'];
779                                         $attachment['preview-height'] = $media[1]['height'];
780                                 }
781                                 $attachments[] = $attachment;
782                         }
783                 }
784
785                 // We have to avoid that the post is rejected because of an empty body
786                 if (empty($_REQUEST['body'])) {
787                         $_REQUEST['body'] = '[hr]';
788                 }
789         }
790
791         if (!empty($attachments)) {
792                 $_REQUEST['attachments'] = $attachments;
793         }
794
795         // set this so that the item_post() function is quiet and doesn't redirect or emit json
796
797         $_REQUEST['api_source'] = true;
798
799         if (empty($_REQUEST['source'])) {
800                 $_REQUEST["source"] = api_source();
801         }
802
803         // call out normal post function
804         $item_id = item_post($a);
805
806         if (!empty($ressources) && !empty($item_id)) {
807                 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
808                 foreach ($ressources as $ressource) {
809                         Photo::setPermissionForRessource($ressource, BaseApi::getCurrentUserID(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
810                 }
811         }
812
813         // output the post that we just posted.
814         return api_status_show($type, $item_id);
815 }
816
817 /// @TODO move to top of file or somewhere better
818 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
819 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
820
821 /**
822  * Uploads an image to Friendica.
823  *
824  * @return array
825  * @throws BadRequestException
826  * @throws ForbiddenException
827  * @throws ImagickException
828  * @throws InternalServerErrorException
829  * @throws UnauthorizedException
830  * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
831  */
832 function api_media_upload()
833 {
834         $a = DI::app();
835
836         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
837
838         if (empty($_FILES['media'])) {
839                 // Output error
840                 throw new BadRequestException("No media.");
841         }
842
843         $media = wall_upload_post($a, false);
844         if (!$media) {
845                 // Output error
846                 throw new InternalServerErrorException();
847         }
848
849         $returndata = [];
850         $returndata["media_id"] = $media["id"];
851         $returndata["media_id_string"] = (string)$media["id"];
852         $returndata["size"] = $media["size"];
853         $returndata["image"] = ["w" => $media["width"],
854                                 "h" => $media["height"],
855                                 "image_type" => $media["type"],
856                                 "friendica_preview_url" => $media["preview"]];
857
858         Logger::info('Media uploaded', ['return' => $returndata]);
859
860         return ["media" => $returndata];
861 }
862
863 /// @TODO move to top of file or somewhere better
864 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
865
866 /**
867  * Updates media meta data (picture descriptions)
868  *
869  * @param string $type Return type (atom, rss, xml, json)
870  *
871  * @return array|string
872  * @throws BadRequestException
873  * @throws ForbiddenException
874  * @throws ImagickException
875  * @throws InternalServerErrorException
876  * @throws TooManyRequestsException
877  * @throws UnauthorizedException
878  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
879  *
880  * @todo Compare the corresponding Twitter function for correct return values
881  */
882 function api_media_metadata_create($type)
883 {
884         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
885
886         $postdata = Network::postdata();
887
888         if (empty($postdata)) {
889                 throw new BadRequestException("No post data");
890         }
891
892         $data = json_decode($postdata, true);
893         if (empty($data)) {
894                 throw new BadRequestException("Invalid post data");
895         }
896
897         if (empty($data['media_id']) || empty($data['alt_text'])) {
898                 throw new BadRequestException("Missing post data values");
899         }
900
901         if (empty($data['alt_text']['text'])) {
902                 throw new BadRequestException("No alt text.");
903         }
904
905         Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
906
907         $condition =  ['id' => $data['media_id'], 'uid' => BaseApi::getCurrentUserID()];
908         $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
909         if (!DBA::isResult($photo)) {
910                 throw new BadRequestException("Metadata not found.");
911         }
912
913         DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
914 }
915
916 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
917
918 /**
919  * @param string $type    Return format (atom, rss, xml, json)
920  * @param int    $item_id
921  * @return array|string
922  * @throws Exception
923  */
924 function api_status_show($type, $item_id)
925 {
926         Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
927
928         $status_info = [];
929
930         $item = api_get_item(['id' => $item_id]);
931         if (!empty($item)) {
932                 $status_info = api_format_item($item, $type);
933         }
934
935         Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
936
937         return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
938 }
939
940 /**
941  * Retrieves the last public status of the provided user info
942  *
943  * @param int    $ownerId Public contact Id
944  * @param int    $uid     User Id
945  * @return array
946  * @throws Exception
947  */
948 function api_get_last_status($ownerId, $uid)
949 {
950         $condition = [
951                 'author-id'=> $ownerId,
952                 'uid'      => $uid,
953                 'gravity'  => [GRAVITY_PARENT, GRAVITY_COMMENT],
954                 'private'  => [Item::PUBLIC, Item::UNLISTED]
955         ];
956
957         $item = api_get_item($condition);
958
959         return $item;
960 }
961
962 /**
963  * Retrieves a single item record based on the provided condition and converts it for API use.
964  *
965  * @param array $condition Item table condition array
966  * @return array
967  * @throws Exception
968  */
969 function api_get_item(array $condition)
970 {
971         $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
972
973         return $item;
974 }
975
976 /**
977  * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
978  * The author's most recent status will be returned inline.
979  *
980  * @param string $type Return type (atom, rss, xml, json)
981  * @return array|string
982  * @throws BadRequestException
983  * @throws ImagickException
984  * @throws InternalServerErrorException
985  * @throws UnauthorizedException
986  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
987  */
988 function api_users_show($type)
989 {
990         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
991
992         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
993
994         $item = api_get_last_status($user_info['pid'], $user_info['uid']);
995         if (!empty($item)) {
996                 $user_info['status'] = api_format_item($item, $type);
997         }
998
999         // "uid" and "self" are only needed for some internal stuff, so remove it from here
1000         unset($user_info['uid']);
1001         unset($user_info['self']);
1002
1003         return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
1004 }
1005
1006 /// @TODO move to top of file or somewhere better
1007 api_register_func('api/users/show', 'api_users_show');
1008 api_register_func('api/externalprofile/show', 'api_users_show');
1009
1010 /**
1011  * Search a public user account.
1012  *
1013  * @param string $type Return type (atom, rss, xml, json)
1014  *
1015  * @return array|string
1016  * @throws BadRequestException
1017  * @throws ImagickException
1018  * @throws InternalServerErrorException
1019  * @throws UnauthorizedException
1020  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1021  */
1022 function api_users_search($type)
1023 {
1024         $userlist = [];
1025
1026         if (!empty($_GET['q'])) {
1027                 $contacts = Contact::selectToArray(
1028                         ['id'],
1029                         [
1030                                 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1031                                 $_GET['q'],
1032                                 $_GET['q'],
1033                                 $_GET['q'],
1034                                 $_GET['q'],
1035                         ]
1036                 );
1037
1038                 if (DBA::isResult($contacts)) {
1039                         $k = 0;
1040                         foreach ($contacts as $contact) {
1041                                 $user_info = DI::twitterUser()->createFromContactId($contact['id'], BaseApi::getCurrentUserID())->toArray();
1042
1043                                 if ($type == 'xml') {
1044                                         $userlist[$k++ . ':user'] = $user_info;
1045                                 } else {
1046                                         $userlist[] = $user_info;
1047                                 }
1048                         }
1049                         $userlist = ['users' => $userlist];
1050                 } else {
1051                         throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1052                 }
1053         } else {
1054                 throw new BadRequestException('No search term specified.');
1055         }
1056
1057         return DI::apiResponse()->formatData('users', $type, $userlist);
1058 }
1059
1060 /// @TODO move to top of file or somewhere better
1061 api_register_func('api/users/search', 'api_users_search');
1062
1063 /**
1064  * Return user objects
1065  *
1066  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1067  *
1068  * @param string $type Return format: json or xml
1069  *
1070  * @return array|string
1071  * @throws BadRequestException
1072  * @throws ImagickException
1073  * @throws InternalServerErrorException
1074  * @throws NotFoundException if the results are empty.
1075  * @throws UnauthorizedException
1076  */
1077 function api_users_lookup($type)
1078 {
1079         $users = [];
1080
1081         if (!empty($_REQUEST['user_id'])) {
1082                 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1083                         if (!empty($id)) {
1084                                 $users[] = api_get_user($id);
1085                         }
1086                 }
1087         }
1088
1089         if (empty($users)) {
1090                 throw new NotFoundException;
1091         }
1092
1093         return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
1094 }
1095
1096 /// @TODO move to top of file or somewhere better
1097 api_register_func('api/users/lookup', 'api_users_lookup', true);
1098
1099 /**
1100  * Returns statuses that match a specified query.
1101  *
1102  * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1103  *
1104  * @param string $type Return format: json, xml, atom, rss
1105  *
1106  * @return array|string
1107  * @throws BadRequestException if the "q" parameter is missing.
1108  * @throws ForbiddenException
1109  * @throws ImagickException
1110  * @throws InternalServerErrorException
1111  * @throws UnauthorizedException
1112  */
1113 function api_search($type)
1114 {
1115         if (empty(BaseApi::getCurrentUserID())) {
1116                 throw new ForbiddenException();
1117         }
1118         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1119
1120         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1121
1122         if (empty($_REQUEST['q'])) {
1123                 throw new BadRequestException('q parameter is required.');
1124         }
1125
1126         $searchTerm = trim(rawurldecode($_REQUEST['q']));
1127
1128         $data = [];
1129         $data['status'] = [];
1130         $count = 15;
1131         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1132         if (!empty($_REQUEST['rpp'])) {
1133                 $count = $_REQUEST['rpp'];
1134         } elseif (!empty($_REQUEST['count'])) {
1135                 $count = $_REQUEST['count'];
1136         }
1137
1138         $since_id = $_REQUEST['since_id'] ?? 0;
1139         $max_id = $_REQUEST['max_id'] ?? 0;
1140         $page = $_REQUEST['page'] ?? 1;
1141
1142         $start = max(0, ($page - 1) * $count);
1143
1144         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1145         if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1146                 $searchTerm = $matches[1];
1147                 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1148                 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1149                 $uriids = [];
1150                 while ($tag = DBA::fetch($tags)) {
1151                         $uriids[] = $tag['uri-id'];
1152                 }
1153                 DBA::close($tags);
1154
1155                 if (empty($uriids)) {
1156                         return DI::apiResponse()->formatData('statuses', $type, $data);
1157                 }
1158
1159                 $condition = ['uri-id' => $uriids];
1160                 if ($exclude_replies) {
1161                         $condition['gravity'] = GRAVITY_PARENT;
1162                 }
1163
1164                 $params['group_by'] = ['uri-id'];
1165         } else {
1166                 $condition = ["`id` > ?
1167                         " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1168                         AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1169                         AND `body` LIKE CONCAT('%',?,'%')",
1170                         $since_id, BaseApi::getCurrentUserID(), $_REQUEST['q']];
1171                 if ($max_id > 0) {
1172                         $condition[0] .= ' AND `id` <= ?';
1173                         $condition[] = $max_id;
1174                 }
1175         }
1176
1177         $statuses = [];
1178
1179         if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1180                 $id = Item::fetchByLink($searchTerm, BaseApi::getCurrentUserID());
1181                 if (!$id) {
1182                         // Public post
1183                         $id = Item::fetchByLink($searchTerm);
1184                 }
1185
1186                 if (!empty($id)) {
1187                         $statuses = Post::select([], ['id' => $id]);
1188                 }
1189         }
1190
1191         $statuses = $statuses ?: Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1192
1193         $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1194
1195         bindComments($data['status']);
1196
1197         return DI::apiResponse()->formatData('statuses', $type, $data);
1198 }
1199
1200 /// @TODO move to top of file or somewhere better
1201 api_register_func('api/search/tweets', 'api_search', true);
1202 api_register_func('api/search', 'api_search', true);
1203
1204 /**
1205  * Returns the most recent statuses posted by the user and the users they follow.
1206  *
1207  * @see  https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1208  *
1209  * @param string $type Return type (atom, rss, xml, json)
1210  *
1211  * @return array|string
1212  * @throws BadRequestException
1213  * @throws ForbiddenException
1214  * @throws ImagickException
1215  * @throws InternalServerErrorException
1216  * @throws UnauthorizedException
1217  * @todo Optional parameters
1218  * @todo Add reply info
1219  */
1220 function api_statuses_home_timeline($type)
1221 {
1222         if (empty(BaseApi::getCurrentUserID())) {
1223                 throw new ForbiddenException();
1224         }
1225         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1226
1227         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1228
1229         unset($_REQUEST["user_id"]);
1230         unset($_GET["user_id"]);
1231
1232         unset($_REQUEST["screen_name"]);
1233         unset($_GET["screen_name"]);
1234
1235         // get last network messages
1236
1237         // params
1238         $count = $_REQUEST['count'] ?? 20;
1239         $page = $_REQUEST['page']?? 0;
1240         $since_id = $_REQUEST['since_id'] ?? 0;
1241         $max_id = $_REQUEST['max_id'] ?? 0;
1242         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1243         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1244
1245         $start = max(0, ($page - 1) * $count);
1246
1247         $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1248                 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1249
1250         if ($max_id > 0) {
1251                 $condition[0] .= " AND `id` <= ?";
1252                 $condition[] = $max_id;
1253         }
1254         if ($exclude_replies) {
1255                 $condition[0] .= ' AND `gravity` = ?';
1256                 $condition[] = GRAVITY_PARENT;
1257         }
1258         if ($conversation_id > 0) {
1259                 $condition[0] .= " AND `parent` = ?";
1260                 $condition[] = $conversation_id;
1261         }
1262
1263         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1264         $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1265
1266         $items = Post::toArray($statuses);
1267
1268         $ret = api_format_items($items, $user_info, false, $type);
1269
1270         // Set all posts from the query above to seen
1271         $idarray = [];
1272         foreach ($items as $item) {
1273                 $idarray[] = intval($item["id"]);
1274         }
1275
1276         if (!empty($idarray)) {
1277                 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1278                 if ($unseen) {
1279                         Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1280                 }
1281         }
1282
1283         bindComments($ret);
1284
1285         $data = ['status' => $ret];
1286         switch ($type) {
1287                 case "atom":
1288                         break;
1289                 case "rss":
1290                         $data = api_rss_extra($data, $user_info);
1291                         break;
1292         }
1293
1294         return DI::apiResponse()->formatData("statuses", $type, $data);
1295 }
1296
1297
1298 /// @TODO move to top of file or somewhere better
1299 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1300 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1301
1302 /**
1303  * Returns the most recent statuses from public users.
1304  *
1305  * @param string $type Return type (atom, rss, xml, json)
1306  *
1307  * @return array|string
1308  * @throws BadRequestException
1309  * @throws ForbiddenException
1310  * @throws ImagickException
1311  * @throws InternalServerErrorException
1312  * @throws UnauthorizedException
1313  */
1314 function api_statuses_public_timeline($type)
1315 {
1316         if (empty(BaseApi::getCurrentUserID())) {
1317                 throw new ForbiddenException();
1318         }
1319         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1320
1321         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1322
1323         // get last network messages
1324
1325         // params
1326         $count = $_REQUEST['count'] ?? 20;
1327         $page = $_REQUEST['page'] ?? 1;
1328         $since_id = $_REQUEST['since_id'] ?? 0;
1329         $max_id = $_REQUEST['max_id'] ?? 0;
1330         $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1331         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1332
1333         $start = max(0, ($page - 1) * $count);
1334
1335         if ($exclude_replies && !$conversation_id) {
1336                 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1337                         GRAVITY_PARENT, $since_id, Item::PUBLIC];
1338
1339                 if ($max_id > 0) {
1340                         $condition[0] .= " AND `id` <= ?";
1341                         $condition[] = $max_id;
1342                 }
1343
1344                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1345                 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1346
1347                 $r = Post::toArray($statuses);
1348         } else {
1349                 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1350                         GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1351
1352                 if ($max_id > 0) {
1353                         $condition[0] .= " AND `id` <= ?";
1354                         $condition[] = $max_id;
1355                 }
1356                 if ($conversation_id > 0) {
1357                         $condition[0] .= " AND `parent` = ?";
1358                         $condition[] = $conversation_id;
1359                 }
1360
1361                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1362                 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1363
1364                 $r = Post::toArray($statuses);
1365         }
1366
1367         $ret = api_format_items($r, $user_info, false, $type);
1368
1369         bindComments($ret);
1370
1371         $data = ['status' => $ret];
1372         switch ($type) {
1373                 case "atom":
1374                         break;
1375                 case "rss":
1376                         $data = api_rss_extra($data, $user_info);
1377                         break;
1378         }
1379
1380         return DI::apiResponse()->formatData("statuses", $type, $data);
1381 }
1382
1383 /// @TODO move to top of file or somewhere better
1384 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1385
1386 /**
1387  * Returns the most recent statuses posted by users this node knows about.
1388  *
1389  * @param string $type Return format: json, xml, atom, rss
1390  * @return array|string
1391  * @throws BadRequestException
1392  * @throws ForbiddenException
1393  * @throws ImagickException
1394  * @throws InternalServerErrorException
1395  * @throws UnauthorizedException
1396  */
1397 function api_statuses_networkpublic_timeline($type)
1398 {
1399         if (empty(BaseApi::getCurrentUserID())) {
1400                 throw new ForbiddenException();
1401         }
1402         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1403
1404         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1405
1406         $since_id        = $_REQUEST['since_id'] ?? 0;
1407         $max_id          = $_REQUEST['max_id'] ?? 0;
1408
1409         // pagination
1410         $count = $_REQUEST['count'] ?? 20;
1411         $page  = $_REQUEST['page'] ?? 1;
1412
1413         $start = max(0, ($page - 1) * $count);
1414
1415         $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1416                 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1417
1418         if ($max_id > 0) {
1419                 $condition[0] .= " AND `id` <= ?";
1420                 $condition[] = $max_id;
1421         }
1422
1423         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1424         $statuses = Post::toArray(Post::selectForUser(BaseApi::getCurrentUserID(), Item::DISPLAY_FIELDLIST, $condition, $params));
1425
1426         $ret = api_format_items($statuses, $user_info, false, $type);
1427
1428         bindComments($ret);
1429
1430         $data = ['status' => $ret];
1431         switch ($type) {
1432                 case "atom":
1433                         break;
1434                 case "rss":
1435                         $data = api_rss_extra($data, $user_info);
1436                         break;
1437         }
1438
1439         return DI::apiResponse()->formatData("statuses", $type, $data);
1440 }
1441
1442 /// @TODO move to top of file or somewhere better
1443 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1444
1445 /**
1446  * Returns a single status.
1447  *
1448  * @param string $type Return type (atom, rss, xml, json)
1449  *
1450  * @return array|string
1451  * @throws BadRequestException
1452  * @throws ForbiddenException
1453  * @throws ImagickException
1454  * @throws InternalServerErrorException
1455  * @throws UnauthorizedException
1456  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1457  */
1458 function api_statuses_show($type)
1459 {
1460         if (empty(BaseApi::getCurrentUserID())) {
1461                 throw new ForbiddenException();
1462         }
1463         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1464
1465         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1466
1467         // params
1468         $id = intval(DI::args()->getArgv()[3] ?? 0);
1469
1470         if ($id == 0) {
1471                 $id = intval($_REQUEST['id'] ?? 0);
1472         }
1473
1474         // Hotot workaround
1475         if ($id == 0) {
1476                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1477         }
1478
1479         logger::notice('API: api_statuses_show: ' . $id);
1480
1481         $conversation = !empty($_REQUEST['conversation']);
1482
1483         // try to fetch the item for the local user - or the public item, if there is no local one
1484         $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1485         if (!DBA::isResult($uri_item)) {
1486                 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1487         }
1488
1489         $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
1490         if (!DBA::isResult($item)) {
1491                 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1492         }
1493
1494         $id = $item['id'];
1495
1496         if ($conversation) {
1497                 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1498                 $params = ['order' => ['id' => true]];
1499         } else {
1500                 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1501                 $params = [];
1502         }
1503
1504         $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1505
1506         /// @TODO How about copying this to above methods which don't check $r ?
1507         if (!DBA::isResult($statuses)) {
1508                 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1509         }
1510
1511         $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1512
1513         if ($conversation) {
1514                 $data = ['status' => $ret];
1515                 return DI::apiResponse()->formatData("statuses", $type, $data);
1516         } else {
1517                 $data = ['status' => $ret[0]];
1518                 return DI::apiResponse()->formatData("status", $type, $data);
1519         }
1520 }
1521
1522 /// @TODO move to top of file or somewhere better
1523 api_register_func('api/statuses/show', 'api_statuses_show', true);
1524
1525 /**
1526  *
1527  * @param string $type Return type (atom, rss, xml, json)
1528  *
1529  * @return array|string
1530  * @throws BadRequestException
1531  * @throws ForbiddenException
1532  * @throws ImagickException
1533  * @throws InternalServerErrorException
1534  * @throws UnauthorizedException
1535  * @todo nothing to say?
1536  */
1537 function api_conversation_show($type)
1538 {
1539         if (empty(BaseApi::getCurrentUserID())) {
1540                 throw new ForbiddenException();
1541         }
1542         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1543
1544         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1545
1546         // params
1547         $id       = intval(DI::args()->getArgv()[3]           ?? 0);
1548         $since_id = intval($_REQUEST['since_id'] ?? 0);
1549         $max_id   = intval($_REQUEST['max_id']   ?? 0);
1550         $count    = intval($_REQUEST['count']    ?? 20);
1551         $page     = intval($_REQUEST['page']     ?? 1);
1552
1553         $start = max(0, ($page - 1) * $count);
1554
1555         if ($id == 0) {
1556                 $id = intval($_REQUEST['id'] ?? 0);
1557         }
1558
1559         // Hotot workaround
1560         if ($id == 0) {
1561                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1562         }
1563
1564         Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1565
1566         // try to fetch the item for the local user - or the public item, if there is no local one
1567         $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1568         if (!DBA::isResult($item)) {
1569                 throw new BadRequestException("There is no status with the id $id.");
1570         }
1571
1572         $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
1573         if (!DBA::isResult($parent)) {
1574                 throw new BadRequestException("There is no status with this id.");
1575         }
1576
1577         $id = $parent['id'];
1578
1579         $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1580                 $id, BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1581
1582         if ($max_id > 0) {
1583                 $condition[0] .= " AND `id` <= ?";
1584                 $condition[] = $max_id;
1585         }
1586
1587         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1588         $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1589
1590         if (!DBA::isResult($statuses)) {
1591                 throw new BadRequestException("There is no status with id $id.");
1592         }
1593
1594         $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1595
1596         $data = ['status' => $ret];
1597         return DI::apiResponse()->formatData("statuses", $type, $data);
1598 }
1599
1600 /// @TODO move to top of file or somewhere better
1601 api_register_func('api/conversation/show', 'api_conversation_show', true);
1602 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1603
1604 /**
1605  * Repeats a status.
1606  *
1607  * @param string $type Return type (atom, rss, xml, json)
1608  *
1609  * @return array|string
1610  * @throws BadRequestException
1611  * @throws ForbiddenException
1612  * @throws ImagickException
1613  * @throws InternalServerErrorException
1614  * @throws UnauthorizedException
1615  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1616  */
1617 function api_statuses_repeat($type)
1618 {
1619         global $called_api;
1620
1621         $a = DI::app();
1622
1623         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1624
1625         // params
1626         $id = intval(DI::args()->getArgv()[3] ?? 0);
1627
1628         if ($id == 0) {
1629                 $id = intval($_REQUEST['id'] ?? 0);
1630         }
1631
1632         // Hotot workaround
1633         if ($id == 0) {
1634                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1635         }
1636
1637         logger::notice('API: api_statuses_repeat: ' . $id);
1638
1639         $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1640         $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1641
1642         if (DBA::isResult($item) && !empty($item['body'])) {
1643                 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1644                         if (!Item::performActivity($id, 'announce', local_user())) {
1645                                 throw new InternalServerErrorException();
1646                         }
1647
1648                         $item_id = $id;
1649                 } else {
1650                         if (strpos($item['body'], "[/share]") !== false) {
1651                                 $pos = strpos($item['body'], "[share");
1652                                 $post = substr($item['body'], $pos);
1653                         } else {
1654                                 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1655
1656                                 if (!empty($item['title'])) {
1657                                         $post .= '[h3]' . $item['title'] . "[/h3]\n";
1658                                 }
1659
1660                                 $post .= $item['body'];
1661                                 $post .= "[/share]";
1662                         }
1663                         $_REQUEST['body'] = $post;
1664                         $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
1665                         $_REQUEST['api_source'] = true;
1666
1667                         if (empty($_REQUEST['source'])) {
1668                                 $_REQUEST["source"] = api_source();
1669                         }
1670
1671                         $item_id = item_post($a);
1672                 }
1673         } else {
1674                 throw new ForbiddenException();
1675         }
1676
1677         // output the post that we just posted.
1678         $called_api = [];
1679         return api_status_show($type, $item_id);
1680 }
1681
1682 /// @TODO move to top of file or somewhere better
1683 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1684
1685 /**
1686  * Destroys a specific status.
1687  *
1688  * @param string $type Return type (atom, rss, xml, json)
1689  *
1690  * @return array|string
1691  * @throws BadRequestException
1692  * @throws ForbiddenException
1693  * @throws ImagickException
1694  * @throws InternalServerErrorException
1695  * @throws UnauthorizedException
1696  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1697  */
1698 function api_statuses_destroy($type)
1699 {
1700         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1701
1702         // params
1703         $id = intval(DI::args()->getArgv()[3] ?? 0);
1704
1705         if ($id == 0) {
1706                 $id = intval($_REQUEST['id'] ?? 0);
1707         }
1708
1709         // Hotot workaround
1710         if ($id == 0) {
1711                 $id = intval(DI::args()->getArgv()[4] ?? 0);
1712         }
1713
1714         logger::notice('API: api_statuses_destroy: ' . $id);
1715
1716         $ret = api_statuses_show($type);
1717
1718         Item::deleteForUser(['id' => $id], BaseApi::getCurrentUserID());
1719
1720         return $ret;
1721 }
1722
1723 /// @TODO move to top of file or somewhere better
1724 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1725
1726 /**
1727  * Returns the most recent mentions.
1728  *
1729  * @param string $type Return type (atom, rss, xml, json)
1730  *
1731  * @return array|string
1732  * @throws BadRequestException
1733  * @throws ForbiddenException
1734  * @throws ImagickException
1735  * @throws InternalServerErrorException
1736  * @throws UnauthorizedException
1737  * @see http://developer.twitter.com/doc/get/statuses/mentions
1738  */
1739 function api_statuses_mentions($type)
1740 {
1741         if (empty(BaseApi::getCurrentUserID())) {
1742                 throw new ForbiddenException();
1743         }
1744         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1745
1746         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1747
1748         unset($_REQUEST["user_id"]);
1749         unset($_GET["user_id"]);
1750
1751         unset($_REQUEST["screen_name"]);
1752         unset($_GET["screen_name"]);
1753
1754         // get last network messages
1755
1756         // params
1757         $since_id = intval($_REQUEST['since_id'] ?? 0);
1758         $max_id   = intval($_REQUEST['max_id']   ?? 0);
1759         $count    = intval($_REQUEST['count']    ?? 20);
1760         $page     = intval($_REQUEST['page']     ?? 1);
1761
1762         $start = max(0, ($page - 1) * $count);
1763
1764         $query = "`gravity` IN (?, ?) AND `uri-id` IN
1765                 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1766                 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1767
1768         $condition = [
1769                 GRAVITY_PARENT, GRAVITY_COMMENT,
1770                 BaseApi::getCurrentUserID(),
1771                 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1772                 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1773                 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1774                 BaseApi::getCurrentUserID(), $since_id,
1775         ];
1776
1777         if ($max_id > 0) {
1778                 $query .= " AND `id` <= ?";
1779                 $condition[] = $max_id;
1780         }
1781
1782         array_unshift($condition, $query);
1783
1784         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1785         $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1786
1787         $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1788
1789         $data = ['status' => $ret];
1790         switch ($type) {
1791                 case "atom":
1792                         break;
1793                 case "rss":
1794                         $data = api_rss_extra($data, $user_info);
1795                         break;
1796         }
1797
1798         return DI::apiResponse()->formatData("statuses", $type, $data);
1799 }
1800
1801 /// @TODO move to top of file or somewhere better
1802 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1803 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1804
1805 /**
1806  * Returns the most recent statuses posted by the user.
1807  *
1808  * @param string $type Either "json" or "xml"
1809  * @return string|array
1810  * @throws BadRequestException
1811  * @throws ForbiddenException
1812  * @throws ImagickException
1813  * @throws InternalServerErrorException
1814  * @throws UnauthorizedException
1815  * @see   https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1816  */
1817 function api_statuses_user_timeline($type)
1818 {
1819         if (empty(BaseApi::getCurrentUserID())) {
1820                 throw new ForbiddenException();
1821         }
1822         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1823
1824         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1825
1826         Logger::info('api_statuses_user_timeline', ['api_user' => BaseApi::getCurrentUserID(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
1827
1828         $since_id        = $_REQUEST['since_id'] ?? 0;
1829         $max_id          = $_REQUEST['max_id'] ?? 0;
1830         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1831         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1832
1833         // pagination
1834         $count = $_REQUEST['count'] ?? 20;
1835         $page  = $_REQUEST['page'] ?? 1;
1836
1837         $start = max(0, ($page - 1) * $count);
1838
1839         $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
1840                 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
1841
1842         if ($user_info['self'] == 1) {
1843                 $condition[0] .= ' AND `wall` ';
1844         }
1845
1846         if ($exclude_replies) {
1847                 $condition[0] .= ' AND `gravity` = ?';
1848                 $condition[] = GRAVITY_PARENT;
1849         }
1850
1851         if ($conversation_id > 0) {
1852                 $condition[0] .= " AND `parent` = ?";
1853                 $condition[] = $conversation_id;
1854         }
1855
1856         if ($max_id > 0) {
1857                 $condition[0] .= " AND `id` <= ?";
1858                 $condition[] = $max_id;
1859         }
1860         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1861         $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1862
1863         $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
1864
1865         bindComments($ret);
1866
1867         $data = ['status' => $ret];
1868         switch ($type) {
1869                 case "atom":
1870                         break;
1871                 case "rss":
1872                         $data = api_rss_extra($data, $user_info);
1873                         break;
1874         }
1875
1876         return DI::apiResponse()->formatData("statuses", $type, $data);
1877 }
1878
1879 /// @TODO move to top of file or somewhere better
1880 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1881
1882 /**
1883  * Star/unstar an item.
1884  * param: id : id of the item
1885  *
1886  * @param string $type Return type (atom, rss, xml, json)
1887  *
1888  * @return array|string
1889  * @throws BadRequestException
1890  * @throws ForbiddenException
1891  * @throws ImagickException
1892  * @throws InternalServerErrorException
1893  * @throws UnauthorizedException
1894  * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1895  */
1896 function api_favorites_create_destroy($type)
1897 {
1898         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1899
1900         // for versioned api.
1901         /// @TODO We need a better global soluton
1902         $action_argv_id = 2;
1903         if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1904                 $action_argv_id = 3;
1905         }
1906
1907         if (DI::args()->getArgc() <= $action_argv_id) {
1908                 throw new BadRequestException("Invalid request.");
1909         }
1910         $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1911         if (DI::args()->getArgc() == $action_argv_id + 2) {
1912                 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1913         } else {
1914                 $itemid = intval($_REQUEST['id'] ?? 0);
1915         }
1916
1917         $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $itemid, 'uid' => BaseApi::getCurrentUserID()]);
1918
1919         if (!DBA::isResult($item)) {
1920                 throw new BadRequestException("Invalid item.");
1921         }
1922
1923         switch ($action) {
1924                 case "create":
1925                         $item['starred'] = 1;
1926                         break;
1927                 case "destroy":
1928                         $item['starred'] = 0;
1929                         break;
1930                 default:
1931                         throw new BadRequestException("Invalid action ".$action);
1932         }
1933
1934         $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1935
1936         if ($r === false) {
1937                 throw new InternalServerErrorException("DB error");
1938         }
1939
1940         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1941         $rets = api_format_items([$item], $user_info, false, $type);
1942         $ret = $rets[0];
1943
1944         $data = ['status' => $ret];
1945         switch ($type) {
1946                 case "atom":
1947                         break;
1948                 case "rss":
1949                         $data = api_rss_extra($data, $user_info);
1950                         break;
1951         }
1952
1953         return DI::apiResponse()->formatData("status", $type, $data);
1954 }
1955
1956 /// @TODO move to top of file or somewhere better
1957 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1958 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1959
1960 /**
1961  * Returns the most recent favorite statuses.
1962  *
1963  * @param string $type Return type (atom, rss, xml, json)
1964  *
1965  * @return string|array
1966  * @throws BadRequestException
1967  * @throws ForbiddenException
1968  * @throws ImagickException
1969  * @throws InternalServerErrorException
1970  * @throws UnauthorizedException
1971  */
1972 function api_favorites($type)
1973 {
1974         global $called_api;
1975
1976         if (empty(BaseApi::getCurrentUserID())) {
1977                 throw new ForbiddenException();
1978         }
1979         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1980
1981         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1982
1983         $called_api = [];
1984
1985         // in friendica starred item are private
1986         // return favorites only for self
1987         Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
1988
1989         if ($user_info['self'] == 0) {
1990                 $ret = [];
1991         } else {
1992                 // params
1993                 $since_id = $_REQUEST['since_id'] ?? 0;
1994                 $max_id = $_REQUEST['max_id'] ?? 0;
1995                 $count = $_GET['count'] ?? 20;
1996                 $page = $_REQUEST['page'] ?? 1;
1997
1998                 $start = max(0, ($page - 1) * $count);
1999
2000                 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2001                         BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2002
2003                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2004
2005                 if ($max_id > 0) {
2006                         $condition[0] .= " AND `id` <= ?";
2007                         $condition[] = $max_id;
2008                 }
2009
2010                 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
2011
2012                 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2013         }
2014
2015         bindComments($ret);
2016
2017         $data = ['status' => $ret];
2018         switch ($type) {
2019                 case "atom":
2020                         break;
2021                 case "rss":
2022                         $data = api_rss_extra($data, $user_info);
2023                         break;
2024         }
2025
2026         return DI::apiResponse()->formatData("statuses", $type, $data);
2027 }
2028
2029 /// @TODO move to top of file or somewhere better
2030 api_register_func('api/favorites', 'api_favorites', true);
2031
2032 /**
2033  *
2034  * @param array $item
2035  * @param array $recipient
2036  * @param array $sender
2037  *
2038  * @return array
2039  * @throws InternalServerErrorException
2040  */
2041 function api_format_messages($item, $recipient, $sender)
2042 {
2043         // standard meta information
2044         $ret = [
2045                 'id'                    => $item['id'],
2046                 'sender_id'             => $sender['id'],
2047                 'text'                  => "",
2048                 'recipient_id'          => $recipient['id'],
2049                 'created_at'            => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2050                 'sender_screen_name'    => $sender['screen_name'],
2051                 'recipient_screen_name' => $recipient['screen_name'],
2052                 'sender'                => $sender,
2053                 'recipient'             => $recipient,
2054                 'title'                 => "",
2055                 'friendica_seen'        => $item['seen'] ?? 0,
2056                 'friendica_parent_uri'  => $item['parent-uri'] ?? '',
2057         ];
2058
2059         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2060         if (isset($ret['sender']['uid'])) {
2061                 unset($ret['sender']['uid']);
2062         }
2063         if (isset($ret['sender']['self'])) {
2064                 unset($ret['sender']['self']);
2065         }
2066         if (isset($ret['recipient']['uid'])) {
2067                 unset($ret['recipient']['uid']);
2068         }
2069         if (isset($ret['recipient']['self'])) {
2070                 unset($ret['recipient']['self']);
2071         }
2072
2073         //don't send title to regular StatusNET requests to avoid confusing these apps
2074         if (!empty($_GET['getText'])) {
2075                 $ret['title'] = $item['title'];
2076                 if ($_GET['getText'] == 'html') {
2077                         $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
2078                 } elseif ($_GET['getText'] == 'plain') {
2079                         $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
2080                 }
2081         } else {
2082                 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
2083         }
2084         if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2085                 unset($ret['sender']);
2086                 unset($ret['recipient']);
2087         }
2088
2089         return $ret;
2090 }
2091
2092 /**
2093  *
2094  * @param array $item
2095  *
2096  * @return array
2097  * @throws InternalServerErrorException
2098  */
2099 function api_convert_item($item)
2100 {
2101         $body = api_add_attachments_to_body($item);
2102
2103         $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2104
2105         // Add pictures to the attachment array and remove them from the body
2106         $attachments = api_get_attachments($body, $item['uri-id']);
2107
2108         // Workaround for ostatus messages where the title is identically to the body
2109         $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
2110         $statusbody = trim(HTML::toPlaintext($html, 0));
2111
2112         // handle data: images
2113         $statusbody = api_format_items_embeded_images($item, $statusbody);
2114
2115         $statustitle = trim($item['title']);
2116
2117         if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2118                 $statustext = trim($statusbody);
2119         } else {
2120                 $statustext = trim($statustitle."\n\n".$statusbody);
2121         }
2122
2123         if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2124                 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2125         }
2126
2127         $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2128
2129         // Workaround for clients with limited HTML parser functionality
2130         $search = ["<br>", "<blockquote>", "</blockquote>",
2131                         "<h1>", "</h1>", "<h2>", "</h2>",
2132                         "<h3>", "</h3>", "<h4>", "</h4>",
2133                         "<h5>", "</h5>", "<h6>", "</h6>"];
2134         $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2135                         "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2136                         "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2137                         "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2138         $statushtml = str_replace($search, $replace, $statushtml);
2139
2140         if ($item['title'] != "") {
2141                 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2142         }
2143
2144         do {
2145                 $oldtext = $statushtml;
2146                 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2147         } while ($oldtext != $statushtml);
2148
2149         if (substr($statushtml, 0, 4) == '<br>') {
2150                 $statushtml = substr($statushtml, 4);
2151         }
2152
2153         if (substr($statushtml, 0, -4) == '<br>') {
2154                 $statushtml = substr($statushtml, -4);
2155         }
2156
2157         // feeds without body should contain the link
2158         if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2159                 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2160         }
2161
2162         return [
2163                 "text" => $statustext,
2164                 "html" => $statushtml,
2165                 "attachments" => $attachments,
2166                 "entities" => $entities
2167         ];
2168 }
2169
2170 /**
2171  * Add media attachments to the body
2172  *
2173  * @param array $item
2174  * @return string body with added media
2175  */
2176 function api_add_attachments_to_body(array $item)
2177 {
2178         $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2179
2180         if (strpos($body, '[/img]') !== false) {
2181                 return $body;
2182         }
2183
2184         foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2185                 if (!empty($media['preview'])) {
2186                         $description = $media['description'] ?: $media['name'];
2187                         if (!empty($description)) {
2188                                 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2189                         } else {
2190                                 $body .= "\n[img]" . $media['preview'] .'[/img]';
2191                         }
2192                 }
2193         }
2194
2195         return $body;
2196 }
2197
2198 /**
2199  *
2200  * @param string $body
2201  * @param int    $uriid
2202  *
2203  * @return array
2204  * @throws InternalServerErrorException
2205  */
2206 function api_get_attachments(&$body, $uriid)
2207 {
2208         $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2209         $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2210
2211         $URLSearchString = "^\[\]";
2212         if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2213                 return [];
2214         }
2215
2216         // Remove all embedded pictures, since they are added as attachments
2217         foreach ($images[0] as $orig) {
2218                 $body = str_replace($orig, '', $body);
2219         }
2220
2221         $attachments = [];
2222
2223         foreach ($images[1] as $image) {
2224                 $imagedata = Images::getInfoFromURLCached($image);
2225
2226                 if ($imagedata) {
2227                         $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2228                 }
2229         }
2230
2231         return $attachments;
2232 }
2233
2234 /**
2235  *
2236  * @param string $text
2237  * @param string $bbcode
2238  *
2239  * @return array
2240  * @throws InternalServerErrorException
2241  * @todo Links at the first character of the post
2242  */
2243 function api_get_entitities(&$text, $bbcode, $uriid)
2244 {
2245         $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2246
2247         if ($include_entities != "true") {
2248                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2249
2250                 foreach ($images[1] as $image) {
2251                         $replace = Post\Link::getByLink($uriid, $image);
2252                         $text = str_replace($image, $replace, $text);
2253                 }
2254                 return [];
2255         }
2256
2257         $bbcode = BBCode::cleanPictureLinks($bbcode);
2258
2259         // Change pure links in text to bbcode uris
2260         $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2261
2262         $entities = [];
2263         $entities["hashtags"] = [];
2264         $entities["symbols"] = [];
2265         $entities["urls"] = [];
2266         $entities["user_mentions"] = [];
2267
2268         $URLSearchString = "^\[\]";
2269
2270         $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2271
2272         $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2273         $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2274
2275         $bbcode = preg_replace(
2276                 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2277                 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2278                 $bbcode
2279         );
2280         $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2281
2282         $bbcode = preg_replace(
2283                 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2284                 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2285                 $bbcode
2286         );
2287         $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2288
2289         $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2290
2291         preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2292
2293         $ordered_urls = [];
2294         foreach ($urls[1] as $id => $url) {
2295                 $start = iconv_strpos($text, $url, 0, "UTF-8");
2296                 if (!($start === false)) {
2297                         $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2298                 }
2299         }
2300
2301         ksort($ordered_urls);
2302
2303         $offset = 0;
2304
2305         foreach ($ordered_urls as $url) {
2306                 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2307                         && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2308                 ) {
2309                         $display_url = $url["title"];
2310                 } else {
2311                         $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2312                         $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2313
2314                         if (strlen($display_url) > 26) {
2315                                 $display_url = substr($display_url, 0, 25)."…";
2316                         }
2317                 }
2318
2319                 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2320                 if (!($start === false)) {
2321                         $entities["urls"][] = ["url" => $url["url"],
2322                                                         "expanded_url" => $url["url"],
2323                                                         "display_url" => $display_url,
2324                                                         "indices" => [$start, $start+strlen($url["url"])]];
2325                         $offset = $start + 1;
2326                 }
2327         }
2328
2329         preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2330         $ordered_images = [];
2331         foreach ($images as $image) {
2332                 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2333                 if (!($start === false)) {
2334                         $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2335                 }
2336         }
2337
2338         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2339         foreach ($images[1] as $image) {
2340                 $start = iconv_strpos($text, $image, 0, "UTF-8");
2341                 if (!($start === false)) {
2342                         $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2343                 }
2344         }
2345
2346         $offset = 0;
2347
2348         foreach ($ordered_images as $image) {
2349                 $url = $image['url'];
2350                 $ext_alt_text = $image['alt'];
2351
2352                 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2353                 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2354
2355                 if (strlen($display_url) > 26) {
2356                         $display_url = substr($display_url, 0, 25)."…";
2357                 }
2358
2359                 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2360                 if (!($start === false)) {
2361                         $image = Images::getInfoFromURLCached($url);
2362                         if ($image) {
2363                                 $media_url = Post\Link::getByLink($uriid, $url);
2364                                 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2365
2366                                 $entities["media"][] = [
2367                                                         "id" => $start+1,
2368                                                         "id_str" => (string) ($start + 1),
2369                                                         "indices" => [$start, $start+strlen($url)],
2370                                                         "media_url" => Strings::normaliseLink($media_url),
2371                                                         "media_url_https" => $media_url,
2372                                                         "url" => $url,
2373                                                         "display_url" => $display_url,
2374                                                         "expanded_url" => $url,
2375                                                         "ext_alt_text" => $ext_alt_text,
2376                                                         "type" => "photo",
2377                                                         "sizes" => $sizes];
2378                         }
2379                         $offset = $start + 1;
2380                 }
2381         }
2382
2383         return $entities;
2384 }
2385
2386 /**
2387  *
2388  * @param array $item
2389  * @param string $text
2390  *
2391  * @return string
2392  */
2393 function api_format_items_embeded_images($item, $text)
2394 {
2395         $text = preg_replace_callback(
2396                 '|data:image/([^;]+)[^=]+=*|m',
2397                 function () use ($item) {
2398                         return DI::baseUrl() . '/display/' . $item['guid'];
2399                 },
2400                 $text
2401         );
2402         return $text;
2403 }
2404
2405 /**
2406  * return <a href='url'>name</a> as array
2407  *
2408  * @param string $txt text
2409  * @return array
2410  *                      'name' => 'name',
2411  *                      'url => 'url'
2412  */
2413 function api_contactlink_to_array($txt)
2414 {
2415         $match = [];
2416         $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2417         if ($r && count($match)==3) {
2418                 $res = [
2419                         'name' => $match[2],
2420                         'url' => $match[1]
2421                 ];
2422         } else {
2423                 $res = [
2424                         'name' => $txt,
2425                         'url' => ""
2426                 ];
2427         }
2428         return $res;
2429 }
2430
2431
2432 /**
2433  * return likes, dislikes and attend status for item
2434  *
2435  * @param array  $item array
2436  * @param string $type Return type (atom, rss, xml, json)
2437  *
2438  * @return array
2439  *            likes => int count,
2440  *            dislikes => int count
2441  * @throws BadRequestException
2442  * @throws ImagickException
2443  * @throws InternalServerErrorException
2444  * @throws UnauthorizedException
2445  */
2446 function api_format_items_activities($item, $type = "json")
2447 {
2448         $activities = [
2449                 'like' => [],
2450                 'dislike' => [],
2451                 'attendyes' => [],
2452                 'attendno' => [],
2453                 'attendmaybe' => [],
2454                 'announce' => [],
2455         ];
2456
2457         $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2458         $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2459
2460         while ($parent_item = Post::fetch($ret)) {
2461                 // not used as result should be structured like other user data
2462                 //builtin_activity_puller($i, $activities);
2463
2464                 // get user data and add it to the array of the activity
2465                 $user = DI::twitterUser()->createFromContactId($parent_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2466                 switch ($parent_item['verb']) {
2467                         case Activity::LIKE:
2468                                 $activities['like'][] = $user;
2469                                 break;
2470                         case Activity::DISLIKE:
2471                                 $activities['dislike'][] = $user;
2472                                 break;
2473                         case Activity::ATTEND:
2474                                 $activities['attendyes'][] = $user;
2475                                 break;
2476                         case Activity::ATTENDNO:
2477                                 $activities['attendno'][] = $user;
2478                                 break;
2479                         case Activity::ATTENDMAYBE:
2480                                 $activities['attendmaybe'][] = $user;
2481                                 break;
2482                         case Activity::ANNOUNCE:
2483                                 $activities['announce'][] = $user;
2484                                 break;
2485                         default:
2486                                 break;
2487                 }
2488         }
2489
2490         DBA::close($ret);
2491
2492         if ($type == "xml") {
2493                 $xml_activities = [];
2494                 foreach ($activities as $k => $v) {
2495                         // change xml element from "like" to "friendica:like"
2496                         $xml_activities["friendica:".$k] = $v;
2497                         // add user data into xml output
2498                         $k_user = 0;
2499                         foreach ($v as $user) {
2500                                 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2501                         }
2502                 }
2503                 $activities = $xml_activities;
2504         }
2505
2506         return $activities;
2507 }
2508
2509 /**
2510  * format items to be returned by api
2511  *
2512  * @param array  $items       array of items
2513  * @param array  $user_info
2514  * @param bool   $filter_user filter items by $user_info
2515  * @param string $type        Return type (atom, rss, xml, json)
2516  * @return array
2517  * @throws BadRequestException
2518  * @throws ImagickException
2519  * @throws InternalServerErrorException
2520  * @throws UnauthorizedException
2521  */
2522 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2523 {
2524         $a = DI::app();
2525
2526         $ret = [];
2527
2528         if (empty($items)) {
2529                 return $ret;
2530         }
2531
2532         foreach ((array)$items as $item) {
2533                 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2534
2535                 // Look if the posts are matching if they should be filtered by user id
2536                 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2537                         continue;
2538                 }
2539
2540                 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2541
2542                 $ret[] = $status;
2543         }
2544
2545         return $ret;
2546 }
2547
2548 /**
2549  * @param array  $item       Item record
2550  * @param string $type       Return format (atom, rss, xml, json)
2551  * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2552  * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2553  * @param array $owner_user  User record of the item owner, can be provided by api_item_get_user()
2554  * @return array API-formatted status
2555  * @throws BadRequestException
2556  * @throws ImagickException
2557  * @throws InternalServerErrorException
2558  * @throws UnauthorizedException
2559  */
2560 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2561 {
2562         $a = DI::app();
2563
2564         if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2565                 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2566         }
2567
2568         DI::contentItem()->localize($item);
2569
2570         $in_reply_to = api_in_reply_to($item);
2571
2572         $converted = api_convert_item($item);
2573
2574         if ($type == "xml") {
2575                 $geo = "georss:point";
2576         } else {
2577                 $geo = "geo";
2578         }
2579
2580         $status = [
2581                 'text'          => $converted["text"],
2582                 'truncated' => false,
2583                 'created_at'=> api_date($item['created']),
2584                 'in_reply_to_status_id' => $in_reply_to['status_id'],
2585                 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2586                 'source'    => (($item['app']) ? $item['app'] : 'web'),
2587                 'id'            => intval($item['id']),
2588                 'id_str'        => (string) intval($item['id']),
2589                 'in_reply_to_user_id' => $in_reply_to['user_id'],
2590                 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2591                 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2592                 $geo => null,
2593                 'favorited' => $item['starred'] ? true : false,
2594                 'user' =>  $status_user,
2595                 'friendica_author' => $author_user,
2596                 'friendica_owner' => $owner_user,
2597                 'friendica_private' => $item['private'] == Item::PRIVATE,
2598                 //'entities' => NULL,
2599                 'statusnet_html' => $converted["html"],
2600                 'statusnet_conversation_id' => $item['parent'],
2601                 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2602                 'friendica_activities' => api_format_items_activities($item, $type),
2603                 'friendica_title' => $item['title'],
2604                 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
2605         ];
2606
2607         if (count($converted["attachments"]) > 0) {
2608                 $status["attachments"] = $converted["attachments"];
2609         }
2610
2611         if (count($converted["entities"]) > 0) {
2612                 $status["entities"] = $converted["entities"];
2613         }
2614
2615         if ($status["source"] == 'web') {
2616                 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2617         } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2618                 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2619         }
2620
2621         $retweeted_item = [];
2622         $quoted_item = [];
2623
2624         if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2625                 $announce = api_get_announce($item);
2626                 if (!empty($announce)) {
2627                         $retweeted_item = $item;
2628                         $item = $announce;
2629                         $status['friendica_owner'] = DI::twitterUser()->createFromContactId($announce['author-id'], BaseApi::getCurrentUserID())->toArray();
2630                 }
2631         }
2632
2633         if (!empty($quoted_item)) {
2634                 if ($quoted_item['id'] != $item['id']) {
2635                         $quoted_status = api_format_item($quoted_item);
2636                         /// @todo Only remove the attachments that are also contained in the quotes status
2637                         unset($status['attachments']);
2638                         unset($status['entities']);
2639                 } else {
2640                         $conv_quoted = api_convert_item($quoted_item);
2641                         $quoted_status = $status;
2642                         unset($quoted_status['attachments']);
2643                         unset($quoted_status['entities']);
2644                         unset($quoted_status['statusnet_conversation_id']);
2645                         $quoted_status['text'] = $conv_quoted['text'];
2646                         $quoted_status['statusnet_html'] = $conv_quoted['html'];
2647                         try {
2648                                 $quoted_status["user"] = DI::twitterUser()->createFromContactId($quoted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2649                         } catch (BadRequestException $e) {
2650                                 // user not found. should be found?
2651                                 /// @todo check if the user should be always found
2652                                 $quoted_status["user"] = [];
2653                         }
2654                 }
2655                 unset($quoted_status['friendica_author']);
2656                 unset($quoted_status['friendica_owner']);
2657                 unset($quoted_status['friendica_activities']);
2658                 unset($quoted_status['friendica_private']);
2659         }
2660
2661         if (!empty($retweeted_item)) {
2662                 $retweeted_status = $status;
2663                 unset($retweeted_status['friendica_author']);
2664                 unset($retweeted_status['friendica_owner']);
2665                 unset($retweeted_status['friendica_activities']);
2666                 unset($retweeted_status['friendica_private']);
2667                 unset($retweeted_status['statusnet_conversation_id']);
2668                 $status['user'] = $status['friendica_owner'];
2669                 try {
2670                         $retweeted_status["user"] = DI::twitterUser()->createFromContactId($retweeted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2671                 } catch (BadRequestException $e) {
2672                         // user not found. should be found?
2673                         /// @todo check if the user should be always found
2674                         $retweeted_status["user"] = [];
2675                 }
2676
2677                 $rt_converted = api_convert_item($retweeted_item);
2678
2679                 $retweeted_status['text'] = $rt_converted["text"];
2680                 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2681                 $retweeted_status['friendica_html'] = $rt_converted["html"];
2682                 $retweeted_status['created_at'] =  api_date($retweeted_item['created']);
2683
2684                 if (!empty($quoted_status)) {
2685                         $retweeted_status['quoted_status'] = $quoted_status;
2686                 }
2687
2688                 $status['friendica_author'] = $retweeted_status['user'];
2689                 $status['retweeted_status'] = $retweeted_status;
2690         } elseif (!empty($quoted_status)) {
2691                 $root_status = api_convert_item($item);
2692
2693                 $status['text'] = $root_status["text"];
2694                 $status['statusnet_html'] = $root_status["html"];
2695                 $status['quoted_status'] = $quoted_status;
2696         }
2697
2698         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2699         unset($status["user"]["uid"]);
2700         unset($status["user"]["self"]);
2701
2702         if ($item["coord"] != "") {
2703                 $coords = explode(' ', $item["coord"]);
2704                 if (count($coords) == 2) {
2705                         if ($type == "json") {
2706                                 $status["geo"] = ['type' => 'Point',
2707                                         'coordinates' => [(float) $coords[0],
2708                                                 (float) $coords[1]]];
2709                         } else {// Not sure if this is the official format - if someone founds a documentation we can check
2710                                 $status["georss:point"] = $item["coord"];
2711                         }
2712                 }
2713         }
2714
2715         return $status;
2716 }
2717
2718 /**
2719  * Returns all lists the user subscribes to.
2720  *
2721  * @param string $type Return type (atom, rss, xml, json)
2722  *
2723  * @return array|string
2724  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2725  */
2726 function api_lists_list($type)
2727 {
2728         $ret = [];
2729         /// @TODO $ret is not filled here?
2730         return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2731 }
2732
2733 /// @TODO move to top of file or somewhere better
2734 api_register_func('api/lists/list', 'api_lists_list', true);
2735 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2736
2737 /**
2738  * Returns all groups the user owns.
2739  *
2740  * @param string $type Return type (atom, rss, xml, json)
2741  *
2742  * @return array|string
2743  * @throws BadRequestException
2744  * @throws ForbiddenException
2745  * @throws ImagickException
2746  * @throws InternalServerErrorException
2747  * @throws UnauthorizedException
2748  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2749  */
2750 function api_lists_ownerships($type)
2751 {
2752         if (empty(BaseApi::getCurrentUserID())) {
2753                 throw new ForbiddenException();
2754         }
2755         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2756
2757         // params
2758         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2759         $uid = $user_info['uid'];
2760
2761         $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2762
2763         // loop through all groups
2764         $lists = [];
2765         foreach ($groups as $group) {
2766                 if ($group['visible']) {
2767                         $mode = 'public';
2768                 } else {
2769                         $mode = 'private';
2770                 }
2771                 $lists[] = [
2772                         'name' => $group['name'],
2773                         'id' => intval($group['id']),
2774                         'id_str' => (string) $group['id'],
2775                         'user' => $user_info,
2776                         'mode' => $mode
2777                 ];
2778         }
2779         return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2780 }
2781
2782 /// @TODO move to top of file or somewhere better
2783 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2784
2785 /**
2786  * Returns recent statuses from users in the specified group.
2787  *
2788  * @param string $type Return type (atom, rss, xml, json)
2789  *
2790  * @return array|string
2791  * @throws BadRequestException
2792  * @throws ForbiddenException
2793  * @throws ImagickException
2794  * @throws InternalServerErrorException
2795  * @throws UnauthorizedException
2796  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2797  */
2798 function api_lists_statuses($type)
2799 {
2800         if (empty(BaseApi::getCurrentUserID())) {
2801                 throw new ForbiddenException();
2802         }
2803         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2804
2805         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2806
2807         unset($_REQUEST["user_id"]);
2808         unset($_GET["user_id"]);
2809
2810         unset($_REQUEST["screen_name"]);
2811         unset($_GET["screen_name"]);
2812
2813         if (empty($_REQUEST['list_id'])) {
2814                 throw new BadRequestException('list_id not specified');
2815         }
2816
2817         // params
2818         $count = $_REQUEST['count'] ?? 20;
2819         $page = $_REQUEST['page'] ?? 1;
2820         $since_id = $_REQUEST['since_id'] ?? 0;
2821         $max_id = $_REQUEST['max_id'] ?? 0;
2822         $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2823         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2824
2825         $start = max(0, ($page - 1) * $count);
2826
2827         $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2828         $gids = array_column($groups, 'contact-id');
2829         $condition = ['uid' => BaseApi::getCurrentUserID(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2830         $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2831
2832         if ($max_id > 0) {
2833                 $condition[0] .= " AND `id` <= ?";
2834                 $condition[] = $max_id;
2835         }
2836         if ($exclude_replies > 0) {
2837                 $condition[0] .= ' AND `gravity` = ?';
2838                 $condition[] = GRAVITY_PARENT;
2839         }
2840         if ($conversation_id > 0) {
2841                 $condition[0] .= " AND `parent` = ?";
2842                 $condition[] = $conversation_id;
2843         }
2844
2845         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2846         $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
2847
2848         $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2849
2850         $data = ['status' => $items];
2851         switch ($type) {
2852                 case "atom":
2853                         break;
2854                 case "rss":
2855                         $data = api_rss_extra($data, $user_info);
2856                         break;
2857         }
2858
2859         return DI::apiResponse()->formatData("statuses", $type, $data);
2860 }
2861
2862 /// @TODO move to top of file or somewhere better
2863 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2864
2865 /**
2866  * Returns either the friends of the follower list
2867  *
2868  * Considers friends and followers lists to be private and won't return
2869  * anything if any user_id parameter is passed.
2870  *
2871  * @param string $qtype Either "friends" or "followers"
2872  * @return boolean|array
2873  * @throws BadRequestException
2874  * @throws ForbiddenException
2875  * @throws ImagickException
2876  * @throws InternalServerErrorException
2877  * @throws UnauthorizedException
2878  */
2879 function api_statuses_f($qtype)
2880 {
2881         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2882
2883         // pagination
2884         $count = $_GET['count'] ?? 20;
2885         $page = $_GET['page'] ?? 1;
2886
2887         $start = max(0, ($page - 1) * $count);
2888
2889         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2890
2891         if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2892                 /* this is to stop Hotot to load friends multiple times
2893                 *  I'm not sure if I'm missing return something or
2894                 *  is a bug in hotot. Workaround, meantime
2895                 */
2896
2897                 /*$ret=Array();
2898                 return array('$users' => $ret);*/
2899                 return false;
2900         }
2901
2902         $sql_extra = '';
2903         if ($qtype == 'friends') {
2904                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2905         } elseif ($qtype == 'followers') {
2906                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2907         }
2908
2909         // friends and followers only for self
2910         if ($user_info['self'] == 0) {
2911                 $sql_extra = " AND false ";
2912         }
2913
2914         if ($qtype == 'blocks') {
2915                 $sql_filter = 'AND `blocked` AND NOT `pending`';
2916         } elseif ($qtype == 'incoming') {
2917                 $sql_filter = 'AND `pending`';
2918         } else {
2919                 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2920         }
2921
2922         // @todo This query most likely can be replaced with a Contact::select...
2923         $r = DBA::toArray(DBA::p(
2924                 "SELECT `id`
2925                 FROM `contact`
2926                 WHERE `uid` = ?
2927                 AND NOT `self`
2928                 $sql_filter
2929                 $sql_extra
2930                 ORDER BY `nick`
2931                 LIMIT ?, ?",
2932                 BaseApi::getCurrentUserID(),
2933                 $start,
2934                 $count
2935         ));
2936
2937         $ret = [];
2938         foreach ($r as $cid) {
2939                 $user = DI::twitterUser()->createFromContactId($cid['id'], BaseApi::getCurrentUserID())->toArray();
2940                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2941                 unset($user["uid"]);
2942                 unset($user["self"]);
2943
2944                 if ($user) {
2945                         $ret[] = $user;
2946                 }
2947         }
2948
2949         return ['user' => $ret];
2950 }
2951
2952
2953 /**
2954  * Returns the list of friends of the provided user
2955  *
2956  * @deprecated By Twitter API in favor of friends/list
2957  *
2958  * @param string $type Either "json" or "xml"
2959  * @return boolean|string|array
2960  * @throws BadRequestException
2961  * @throws ForbiddenException
2962  */
2963 function api_statuses_friends($type)
2964 {
2965         $data =  api_statuses_f("friends");
2966         if ($data === false) {
2967                 return false;
2968         }
2969         return DI::apiResponse()->formatData("users", $type, $data);
2970 }
2971
2972 /**
2973  * Returns the list of followers of the provided user
2974  *
2975  * @deprecated By Twitter API in favor of friends/list
2976  *
2977  * @param string $type Either "json" or "xml"
2978  * @return boolean|string|array
2979  * @throws BadRequestException
2980  * @throws ForbiddenException
2981  */
2982 function api_statuses_followers($type)
2983 {
2984         $data = api_statuses_f("followers");
2985         if ($data === false) {
2986                 return false;
2987         }
2988         return DI::apiResponse()->formatData("users", $type, $data);
2989 }
2990
2991 /// @TODO move to top of file or somewhere better
2992 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2993 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2994
2995 /**
2996  * Returns the list of blocked users
2997  *
2998  * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
2999  *
3000  * @param string $type Either "json" or "xml"
3001  *
3002  * @return boolean|string|array
3003  * @throws BadRequestException
3004  * @throws ForbiddenException
3005  */
3006 function api_blocks_list($type)
3007 {
3008         $data =  api_statuses_f('blocks');
3009         if ($data === false) {
3010                 return false;
3011         }
3012         return DI::apiResponse()->formatData("users", $type, $data);
3013 }
3014
3015 /// @TODO move to top of file or somewhere better
3016 api_register_func('api/blocks/list', 'api_blocks_list', true);
3017
3018 /**
3019  * Returns the list of pending users IDs
3020  *
3021  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3022  *
3023  * @param string $type Either "json" or "xml"
3024  *
3025  * @return boolean|string|array
3026  * @throws BadRequestException
3027  * @throws ForbiddenException
3028  */
3029 function api_friendships_incoming($type)
3030 {
3031         $data =  api_statuses_f('incoming');
3032         if ($data === false) {
3033                 return false;
3034         }
3035
3036         $ids = [];
3037         foreach ($data['user'] as $user) {
3038                 $ids[] = $user['id'];
3039         }
3040
3041         return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
3042 }
3043
3044 /// @TODO move to top of file or somewhere better
3045 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3046
3047 /**
3048  * Sends a new direct message.
3049  *
3050  * @param string $type Return type (atom, rss, xml, json)
3051  *
3052  * @return array|string
3053  * @throws BadRequestException
3054  * @throws ForbiddenException
3055  * @throws ImagickException
3056  * @throws InternalServerErrorException
3057  * @throws NotFoundException
3058  * @throws UnauthorizedException
3059  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3060  */
3061 function api_direct_messages_new($type)
3062 {
3063         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3064
3065         $uid = BaseApi::getCurrentUserID();
3066         if (empty($uid)) {
3067                 throw new ForbiddenException();
3068         }
3069
3070         if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3071                 return;
3072         }
3073
3074         $sender = DI::twitterUser()->createFromUserId($uid)->toArray();
3075
3076         $recipient = null;
3077         if (!empty($_POST['screen_name'])) {
3078                 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => BaseApi::getCurrentUserID(), 'nick' => $_POST['screen_name']]);
3079                 if (DBA::isResult($contacts)) {
3080                         // Selecting the id by priority, friendica first
3081                         api_best_nickname($contacts);
3082
3083                         $recipient = DI::twitterUser()->createFromContactId($contacts[0]['id'], $uid)->toArray();
3084                 }
3085         } else {
3086                 $recipient = api_get_user($_POST['user_id']);
3087         }
3088
3089         if (empty($recipient)) {
3090                 throw new NotFoundException('Recipient not found');
3091         }
3092
3093         $replyto = '';
3094         if (!empty($_REQUEST['replyto'])) {
3095                 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $_REQUEST['replyto']]);
3096                 $replyto = $mail['parent-uri'];
3097                 $sub     = $mail['title'];
3098         } else {
3099                 if (!empty($_REQUEST['title'])) {
3100                         $sub = $_REQUEST['title'];
3101                 } else {
3102                         $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3103                 }
3104         }
3105
3106         $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3107
3108         if ($id > -1) {
3109                 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
3110                 $ret = api_format_messages($mail, $recipient, $sender);
3111         } else {
3112                 $ret = ["error" => $id];
3113         }
3114
3115         $data = ['direct_message'=>$ret];
3116
3117         switch ($type) {
3118                 case "atom":
3119                         break;
3120                 case "rss":
3121                         $data = api_rss_extra($data, $sender);
3122                         break;
3123         }
3124
3125         return DI::apiResponse()->formatData("direct-messages", $type, $data);
3126 }
3127
3128 /// @TODO move to top of file or somewhere better
3129 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3130
3131 /**
3132  * delete a direct_message from mail table through api
3133  *
3134  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3135  * @return string|array
3136  * @throws BadRequestException
3137  * @throws ForbiddenException
3138  * @throws ImagickException
3139  * @throws InternalServerErrorException
3140  * @throws UnauthorizedException
3141  * @see   https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3142  */
3143 function api_direct_messages_destroy($type)
3144 {
3145         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3146
3147         // params
3148         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3149         //required
3150         $id = $_REQUEST['id'] ?? 0;
3151         // optional
3152         $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3153         $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3154         /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3155
3156         $uid = $user_info['uid'];
3157         // error if no id or parenturi specified (for clients posting parent-uri as well)
3158         if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3159                 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3160                 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3161         }
3162
3163         // BadRequestException if no id specified (for clients using Twitter API)
3164         if ($id == 0) {
3165                 throw new BadRequestException('Message id not specified');
3166         }
3167
3168         // add parent-uri to sql command if specified by calling app
3169         $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3170
3171         // error message if specified id is not in database
3172         if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
3173                 if ($verbose == "true") {
3174                         $answer = ['result' => 'error', 'message' => 'message id not in database'];
3175                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3176                 }
3177                 /// @todo BadRequestException ok for Twitter API clients?
3178                 throw new BadRequestException('message id not in database');
3179         }
3180
3181         // delete message
3182         $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
3183
3184         if ($verbose == "true") {
3185                 if ($result) {
3186                         // return success
3187                         $answer = ['result' => 'ok', 'message' => 'message deleted'];
3188                         return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
3189                 } else {
3190                         $answer = ['result' => 'error', 'message' => 'unknown error'];
3191                         return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3192                 }
3193         }
3194         /// @todo return JSON data like Twitter API not yet implemented
3195 }
3196
3197 /// @TODO move to top of file or somewhere better
3198 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3199
3200 /**
3201  * Unfollow Contact
3202  *
3203  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3204  * @return string|array
3205  * @throws HTTPException\BadRequestException
3206  * @throws HTTPException\ExpectationFailedException
3207  * @throws HTTPException\ForbiddenException
3208  * @throws HTTPException\InternalServerErrorException
3209  * @throws HTTPException\NotFoundException
3210  * @see   https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3211  */
3212 function api_friendships_destroy($type)
3213 {
3214         $uid = BaseApi::getCurrentUserID();
3215
3216         if ($uid === false) {
3217                 throw new HTTPException\ForbiddenException();
3218         }
3219
3220         $owner = User::getOwnerDataById($uid);
3221         if (!$owner) {
3222                 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3223                 throw new HTTPException\NotFoundException('Error Processing Request');
3224         }
3225
3226         $contact_id = $_REQUEST['user_id'] ?? 0;
3227
3228         if (empty($contact_id)) {
3229                 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3230                 throw new HTTPException\BadRequestException('no user_id specified');
3231         }
3232
3233         // Get Contact by given id
3234         $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3235
3236         if(!DBA::isResult($contact)) {
3237                 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3238                 throw new HTTPException\NotFoundException('no contact found to given ID');
3239         }
3240
3241         $url = $contact['url'];
3242
3243         $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3244                         $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3245                         Strings::normaliseLink($url), $url];
3246         $contact = DBA::selectFirst('contact', [], $condition);
3247
3248         if (!DBA::isResult($contact)) {
3249                 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3250                 throw new HTTPException\NotFoundException('Not following Contact');
3251         }
3252
3253         try {
3254                 $result = Contact::terminateFriendship($owner, $contact);
3255
3256                 if ($result === null) {
3257                         Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3258                         throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3259                 }
3260
3261                 if ($result === false) {
3262                         throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3263                 }
3264         } catch (Exception $e) {
3265                 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3266                 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3267         }
3268
3269         // "uid" and "self" are only needed for some internal stuff, so remove it from here
3270         unset($contact['uid']);
3271         unset($contact['self']);
3272
3273         // Set screen_name since Twidere requests it
3274         $contact['screen_name'] = $contact['nick'];
3275
3276         return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
3277 }
3278
3279 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3280
3281 /**
3282  *
3283  * @param string $type Return type (atom, rss, xml, json)
3284  * @param string $box
3285  * @param string $verbose
3286  *
3287  * @return array|string
3288  * @throws BadRequestException
3289  * @throws ForbiddenException
3290  * @throws ImagickException
3291  * @throws InternalServerErrorException
3292  * @throws UnauthorizedException
3293  */
3294 function api_direct_messages_box($type, $box, $verbose)
3295 {
3296         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3297
3298         // params
3299         $count = $_GET['count'] ?? 20;
3300         $page = $_REQUEST['page'] ?? 1;
3301
3302         $since_id = $_REQUEST['since_id'] ?? 0;
3303         $max_id = $_REQUEST['max_id'] ?? 0;
3304
3305         $user_id = $_REQUEST['user_id'] ?? '';
3306         $screen_name = $_REQUEST['screen_name'] ?? '';
3307
3308         //  caller user info
3309         unset($_REQUEST["user_id"]);
3310         unset($_GET["user_id"]);
3311
3312         unset($_REQUEST["screen_name"]);
3313         unset($_GET["screen_name"]);
3314
3315         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3316
3317         $profile_url = $user_info["url"];
3318
3319         // pagination
3320         $start = max(0, ($page - 1) * $count);
3321
3322         $sql_extra = "";
3323
3324         // filters
3325         if ($box=="sentbox") {
3326                 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3327         } elseif ($box == "conversation") {
3328                 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '')  . "'";
3329         } elseif ($box == "all") {
3330                 $sql_extra = "true";
3331         } elseif ($box == "inbox") {
3332                 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3333         }
3334
3335         if ($max_id > 0) {
3336                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3337         }
3338
3339         if ($user_id != "") {
3340                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3341         } elseif ($screen_name !="") {
3342                 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3343         }
3344
3345         $r = DBA::toArray(DBA::p(
3346                 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND $sql_extra AND `mail`.`id` > ? ORDER BY `mail`.`id` DESC LIMIT ?,?",
3347                 BaseApi::getCurrentUserID(),
3348                 $since_id,
3349                 $start,
3350                 $count
3351         ));
3352         if ($verbose == "true" && !DBA::isResult($r)) {
3353                 $answer = ['result' => 'error', 'message' => 'no mails available'];
3354                 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
3355         }
3356
3357         $ret = [];
3358         foreach ($r as $item) {
3359                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3360                         $recipient = $user_info;
3361                         $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
3362                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3363                         $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
3364                         $sender = $user_info;
3365                 }
3366
3367                 if (isset($recipient) && isset($sender)) {
3368                         $ret[] = api_format_messages($item, $recipient, $sender);
3369                 }
3370         }
3371
3372
3373         $data = ['direct_message' => $ret];
3374         switch ($type) {
3375                 case "atom":
3376                         break;
3377                 case "rss":
3378                         $data = api_rss_extra($data, $user_info);
3379                         break;
3380         }
3381
3382         return DI::apiResponse()->formatData("direct-messages", $type, $data);
3383 }
3384
3385 /**
3386  * Returns the most recent direct messages sent by the user.
3387  *
3388  * @param string $type Return type (atom, rss, xml, json)
3389  *
3390  * @return array|string
3391  * @throws BadRequestException
3392  * @throws ForbiddenException
3393  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3394  */
3395 function api_direct_messages_sentbox($type)
3396 {
3397         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3398         return api_direct_messages_box($type, "sentbox", $verbose);
3399 }
3400
3401 /**
3402  * Returns the most recent direct messages sent to the user.
3403  *
3404  * @param string $type Return type (atom, rss, xml, json)
3405  *
3406  * @return array|string
3407  * @throws BadRequestException
3408  * @throws ForbiddenException
3409  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3410  */
3411 function api_direct_messages_inbox($type)
3412 {
3413         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3414         return api_direct_messages_box($type, "inbox", $verbose);
3415 }
3416
3417 /**
3418  *
3419  * @param string $type Return type (atom, rss, xml, json)
3420  *
3421  * @return array|string
3422  * @throws BadRequestException
3423  * @throws ForbiddenException
3424  */
3425 function api_direct_messages_all($type)
3426 {
3427         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3428         return api_direct_messages_box($type, "all", $verbose);
3429 }
3430
3431 /**
3432  *
3433  * @param string $type Return type (atom, rss, xml, json)
3434  *
3435  * @return array|string
3436  * @throws BadRequestException
3437  * @throws ForbiddenException
3438  */
3439 function api_direct_messages_conversation($type)
3440 {
3441         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3442         return api_direct_messages_box($type, "conversation", $verbose);
3443 }
3444
3445 /// @TODO move to top of file or somewhere better
3446 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3447 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3448 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3449 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3450
3451 /**
3452  * list all photos of the authenticated user
3453  *
3454  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3455  * @return string|array
3456  * @throws ForbiddenException
3457  * @throws InternalServerErrorException
3458  */
3459 function api_fr_photos_list($type)
3460 {
3461         if (BaseApi::getCurrentUserID() === false) {
3462                 throw new ForbiddenException();
3463         }
3464         $r = DBA::toArray(DBA::p(
3465                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3466                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3467                 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
3468                 local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
3469         ));
3470         $typetoext = [
3471                 'image/jpeg' => 'jpg',
3472                 'image/png' => 'png',
3473                 'image/gif' => 'gif'
3474         ];
3475         $data = ['photo'=>[]];
3476         if (DBA::isResult($r)) {
3477                 foreach ($r as $rr) {
3478                         $photo = [];
3479                         $photo['id'] = $rr['resource-id'];
3480                         $photo['album'] = $rr['album'];
3481                         $photo['filename'] = $rr['filename'];
3482                         $photo['type'] = $rr['type'];
3483                         $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3484                         $photo['created'] = $rr['created'];
3485                         $photo['edited'] = $rr['edited'];
3486                         $photo['desc'] = $rr['desc'];
3487
3488                         if ($type == "xml") {
3489                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3490                         } else {
3491                                 $photo['thumb'] = $thumb;
3492                                 $data['photo'][] = $photo;
3493                         }
3494                 }
3495         }
3496         return DI::apiResponse()->formatData("photos", $type, $data);
3497 }
3498
3499 /**
3500  * upload a new photo or change an existing photo
3501  *
3502  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3503  * @return string|array
3504  * @throws BadRequestException
3505  * @throws ForbiddenException
3506  * @throws ImagickException
3507  * @throws InternalServerErrorException
3508  * @throws NotFoundException
3509  */
3510 function api_fr_photo_create_update($type)
3511 {
3512         if (BaseApi::getCurrentUserID() === false) {
3513                 throw new ForbiddenException();
3514         }
3515         // input params
3516         $photo_id  = $_REQUEST['photo_id']  ?? null;
3517         $desc      = $_REQUEST['desc']      ?? null;
3518         $album     = $_REQUEST['album']     ?? null;
3519         $album_new = $_REQUEST['album_new'] ?? null;
3520         $allow_cid = $_REQUEST['allow_cid'] ?? null;
3521         $deny_cid  = $_REQUEST['deny_cid' ] ?? null;
3522         $allow_gid = $_REQUEST['allow_gid'] ?? null;
3523         $deny_gid  = $_REQUEST['deny_gid' ] ?? null;
3524         $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3525
3526         // do several checks on input parameters
3527         // we do not allow calls without album string
3528         if ($album == null) {
3529                 throw new BadRequestException("no albumname specified");
3530         }
3531         // if photo_id == null --> we are uploading a new photo
3532         if ($photo_id == null) {
3533                 $mode = "create";
3534
3535                 // error if no media posted in create-mode
3536                 if (empty($_FILES['media'])) {
3537                         // Output error
3538                         throw new BadRequestException("no media data submitted");
3539                 }
3540
3541                 // album_new will be ignored in create-mode
3542                 $album_new = "";
3543         } else {
3544                 $mode = "update";
3545
3546                 // check if photo is existing in databasei
3547                 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => BaseApi::getCurrentUserID(), 'album' => $album])) {
3548                         throw new BadRequestException("photo not available");
3549                 }
3550         }
3551
3552         // checks on acl strings provided by clients
3553         $acl_input_error = false;
3554         $acl_input_error |= check_acl_input($allow_cid);
3555         $acl_input_error |= check_acl_input($deny_cid);
3556         $acl_input_error |= check_acl_input($allow_gid);
3557         $acl_input_error |= check_acl_input($deny_gid);
3558         if ($acl_input_error) {
3559                 throw new BadRequestException("acl data invalid");
3560         }
3561         // now let's upload the new media in create-mode
3562         if ($mode == "create") {
3563                 $media = $_FILES['media'];
3564                 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, Photo::DEFAULT, $visibility);
3565
3566                 // return success of updating or error message
3567                 if (!is_null($data)) {
3568                         return DI::apiResponse()->formatData("photo_create", $type, $data);
3569                 } else {
3570                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3571                 }
3572         }
3573
3574         // now let's do the changes in update-mode
3575         if ($mode == "update") {
3576                 $updated_fields = [];
3577
3578                 if (!is_null($desc)) {
3579                         $updated_fields['desc'] = $desc;
3580                 }
3581
3582                 if (!is_null($album_new)) {
3583                         $updated_fields['album'] = $album_new;
3584                 }
3585
3586                 if (!is_null($allow_cid)) {
3587                         $allow_cid = trim($allow_cid);
3588                         $updated_fields['allow_cid'] = $allow_cid;
3589                 }
3590
3591                 if (!is_null($deny_cid)) {
3592                         $deny_cid = trim($deny_cid);
3593                         $updated_fields['deny_cid'] = $deny_cid;
3594                 }
3595
3596                 if (!is_null($allow_gid)) {
3597                         $allow_gid = trim($allow_gid);
3598                         $updated_fields['allow_gid'] = $allow_gid;
3599                 }
3600
3601                 if (!is_null($deny_gid)) {
3602                         $deny_gid = trim($deny_gid);
3603                         $updated_fields['deny_gid'] = $deny_gid;
3604                 }
3605
3606                 $result = false;
3607                 if (count($updated_fields) > 0) {
3608                         $nothingtodo = false;
3609                         $result = Photo::update($updated_fields, ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id, 'album' => $album]);
3610                 } else {
3611                         $nothingtodo = true;
3612                 }
3613
3614                 if (!empty($_FILES['media'])) {
3615                         $nothingtodo = false;
3616                         $media = $_FILES['media'];
3617                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
3618                         if (!is_null($data)) {
3619                                 return DI::apiResponse()->formatData("photo_update", $type, $data);
3620                         }
3621                 }
3622
3623                 // return success of updating or error message
3624                 if ($result) {
3625                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3626                         return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3627                 } else {
3628                         if ($nothingtodo) {
3629                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3630                                 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3631                         }
3632                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3633                 }
3634         }
3635         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3636 }
3637
3638 /**
3639  * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3640  *
3641  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3642  * @return string|array
3643  * @throws BadRequestException
3644  * @throws ForbiddenException
3645  * @throws InternalServerErrorException
3646  * @throws NotFoundException
3647  */
3648 function api_fr_photo_detail($type)
3649 {
3650         if (BaseApi::getCurrentUserID() === false) {
3651                 throw new ForbiddenException();
3652         }
3653         if (empty($_REQUEST['photo_id'])) {
3654                 throw new BadRequestException("No photo id.");
3655         }
3656
3657         $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3658         $photo_id = $_REQUEST['photo_id'];
3659
3660         // prepare json/xml output with data from database for the requested photo
3661         $data = prepare_photo_data($type, $scale, $photo_id);
3662
3663         return DI::apiResponse()->formatData("photo_detail", $type, $data);
3664 }
3665
3666
3667 /**
3668  * updates the profile image for the user (either a specified profile or the default profile)
3669  *
3670  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3671  *
3672  * @return string|array
3673  * @throws BadRequestException
3674  * @throws ForbiddenException
3675  * @throws ImagickException
3676  * @throws InternalServerErrorException
3677  * @throws NotFoundException
3678  * @see   https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3679  */
3680 function api_account_update_profile_image($type)
3681 {
3682         if (BaseApi::getCurrentUserID() === false) {
3683                 throw new ForbiddenException();
3684         }
3685         // input params
3686         $profile_id = $_REQUEST['profile_id'] ?? 0;
3687
3688         // error if image data is missing
3689         if (empty($_FILES['image'])) {
3690                 throw new BadRequestException("no media data submitted");
3691         }
3692
3693         // check if specified profile id is valid
3694         if ($profile_id != 0) {
3695                 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $profile_id]);
3696                 // error message if specified profile id is not in database
3697                 if (!DBA::isResult($profile)) {
3698                         throw new BadRequestException("profile_id not available");
3699                 }
3700                 $is_default_profile = $profile['is-default'];
3701         } else {
3702                 $is_default_profile = 1;
3703         }
3704
3705         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3706         $media = null;
3707         if (!empty($_FILES['image'])) {
3708                 $media = $_FILES['image'];
3709         } elseif (!empty($_FILES['media'])) {
3710                 $media = $_FILES['media'];
3711         }
3712         // save new profile image
3713         $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
3714
3715         // get filetype
3716         if (is_array($media['type'])) {
3717                 $filetype = $media['type'][0];
3718         } else {
3719                 $filetype = $media['type'];
3720         }
3721         if ($filetype == "image/jpeg") {
3722                 $fileext = "jpg";
3723         } elseif ($filetype == "image/png") {
3724                 $fileext = "png";
3725         } else {
3726                 throw new InternalServerErrorException('Unsupported filetype');
3727         }
3728
3729         // change specified profile or all profiles to the new resource-id
3730         if ($is_default_profile) {
3731                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], BaseApi::getCurrentUserID()];
3732                 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3733         } else {
3734                 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3735                         'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3736                 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => BaseApi::getCurrentUserID()]);
3737         }
3738
3739         Contact::updateSelfFromUserID(BaseApi::getCurrentUserID(), true);
3740
3741         // Update global directory in background
3742         Profile::publishUpdate(BaseApi::getCurrentUserID());
3743
3744         // output for client
3745         if ($data) {
3746                 return api_account_verify_credentials($type);
3747         } else {
3748                 // SaveMediaToDatabase failed for some reason
3749                 throw new InternalServerErrorException("image upload failed");
3750         }
3751 }
3752
3753 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3754 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3755 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3756 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3757 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3758 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3759
3760 /**
3761  * Update user profile
3762  *
3763  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3764  *
3765  * @return array|string
3766  * @throws BadRequestException
3767  * @throws ForbiddenException
3768  * @throws ImagickException
3769  * @throws InternalServerErrorException
3770  * @throws UnauthorizedException
3771  */
3772 function api_account_update_profile($type)
3773 {
3774         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3775
3776         $local_user = BaseApi::getCurrentUserID();
3777
3778         $api_user = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3779
3780         if (!empty($_POST['name'])) {
3781                 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
3782                 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
3783                 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
3784                 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3785         }
3786
3787         if (isset($_POST['description'])) {
3788                 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
3789                 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
3790                 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3791         }
3792
3793         Profile::publishUpdate($local_user);
3794
3795         return api_account_verify_credentials($type);
3796 }
3797
3798 /// @TODO move to top of file or somewhere better
3799 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3800
3801 /**
3802  *
3803  * @param string $acl_string
3804  * @return bool
3805  * @throws Exception
3806  */
3807 function check_acl_input($acl_string)
3808 {
3809         if (empty($acl_string)) {
3810                 return false;
3811         }
3812
3813         $contact_not_found = false;
3814
3815         // split <x><y><z> into array of cid's
3816         preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3817
3818         // check for each cid if it is available on server
3819         $cid_array = $array[0];
3820         foreach ($cid_array as $cid) {
3821                 $cid = str_replace("<", "", $cid);
3822                 $cid = str_replace(">", "", $cid);
3823                 $condition = ['id' => $cid, 'uid' => BaseApi::getCurrentUserID()];
3824                 $contact_not_found |= !DBA::exists('contact', $condition);
3825         }
3826         return $contact_not_found;
3827 }
3828
3829 /**
3830  * @param string  $mediatype
3831  * @param array   $media
3832  * @param string  $type
3833  * @param string  $album
3834  * @param string  $allow_cid
3835  * @param string  $deny_cid
3836  * @param string  $allow_gid
3837  * @param string  $deny_gid
3838  * @param string  $desc
3839  * @param integer $phototype
3840  * @param boolean $visibility
3841  * @param string  $photo_id
3842  * @return array
3843  * @throws BadRequestException
3844  * @throws ForbiddenException
3845  * @throws ImagickException
3846  * @throws InternalServerErrorException
3847  * @throws NotFoundException
3848  * @throws UnauthorizedException
3849  */
3850 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype = 0, $visibility = false, $photo_id = null)
3851 {
3852         $visitor   = 0;
3853         $src = "";
3854         $filetype = "";
3855         $filename = "";
3856         $filesize = 0;
3857
3858         if (is_array($media)) {
3859                 if (is_array($media['tmp_name'])) {
3860                         $src = $media['tmp_name'][0];
3861                 } else {
3862                         $src = $media['tmp_name'];
3863                 }
3864                 if (is_array($media['name'])) {
3865                         $filename = basename($media['name'][0]);
3866                 } else {
3867                         $filename = basename($media['name']);
3868                 }
3869                 if (is_array($media['size'])) {
3870                         $filesize = intval($media['size'][0]);
3871                 } else {
3872                         $filesize = intval($media['size']);
3873                 }
3874                 if (is_array($media['type'])) {
3875                         $filetype = $media['type'][0];
3876                 } else {
3877                         $filetype = $media['type'];
3878                 }
3879         }
3880
3881         $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
3882
3883         logger::info(
3884                 "File upload src: " . $src . " - filename: " . $filename .
3885                 " - size: " . $filesize . " - type: " . $filetype);
3886
3887         // check if there was a php upload error
3888         if ($filesize == 0 && $media['error'] == 1) {
3889                 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3890         }
3891         // check against max upload size within Friendica instance
3892         $maximagesize = DI::config()->get('system', 'maximagesize');
3893         if ($maximagesize && ($filesize > $maximagesize)) {
3894                 $formattedBytes = Strings::formatBytes($maximagesize);
3895                 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3896         }
3897
3898         // create Photo instance with the data of the image
3899         $imagedata = @file_get_contents($src);
3900         $Image = new Image($imagedata, $filetype);
3901         if (!$Image->isValid()) {
3902                 throw new InternalServerErrorException("unable to process image data");
3903         }
3904
3905         // check orientation of image
3906         $Image->orient($src);
3907         @unlink($src);
3908
3909         // check max length of images on server
3910         $max_length = DI::config()->get('system', 'max_image_length');
3911         if ($max_length > 0) {
3912                 $Image->scaleDown($max_length);
3913                 logger::info("File upload: Scaling picture to new size " . $max_length);
3914         }
3915         $width = $Image->getWidth();
3916         $height = $Image->getHeight();
3917
3918         // create a new resource-id if not already provided
3919         $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
3920
3921         if ($mediatype == "photo") {
3922                 // upload normal image (scales 0, 1, 2)
3923                 logger::info("photo upload: starting new photo upload");
3924
3925                 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3926                 if (!$r) {
3927                         logger::notice("photo upload: image upload with scale 0 (original size) failed");
3928                 }
3929                 if ($width > 640 || $height > 640) {
3930                         $Image->scaleDown(640);
3931                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3932                         if (!$r) {
3933                                 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
3934                         }
3935                 }
3936
3937                 if ($width > 320 || $height > 320) {
3938                         $Image->scaleDown(320);
3939                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3940                         if (!$r) {
3941                                 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
3942                         }
3943                 }
3944                 logger::info("photo upload: new photo upload ended");
3945         } elseif ($mediatype == "profileimage") {
3946                 // upload profile image (scales 4, 5, 6)
3947                 logger::info("photo upload: starting new profile image upload");
3948
3949                 if ($width > 300 || $height > 300) {
3950                         $Image->scaleDown(300);
3951                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3952                         if (!$r) {
3953                                 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
3954                         }
3955                 }
3956
3957                 if ($width > 80 || $height > 80) {
3958                         $Image->scaleDown(80);
3959                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3960                         if (!$r) {
3961                                 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
3962                         }
3963                 }
3964
3965                 if ($width > 48 || $height > 48) {
3966                         $Image->scaleDown(48);
3967                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3968                         if (!$r) {
3969                                 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
3970                         }
3971                 }
3972                 $Image->__destruct();
3973                 logger::info("photo upload: new profile image upload ended");
3974         }
3975
3976         if (!empty($r)) {
3977                 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3978                 if ($photo_id == null && $mediatype == "photo") {
3979                         post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
3980                 }
3981                 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3982                 return prepare_photo_data($type, false, $resource_id);
3983         } else {
3984                 throw new InternalServerErrorException("image upload failed");
3985         }
3986 }
3987
3988 /**
3989  *
3990  * @param string  $hash
3991  * @param string  $allow_cid
3992  * @param string  $deny_cid
3993  * @param string  $allow_gid
3994  * @param string  $deny_gid
3995  * @param string  $filetype
3996  * @param boolean $visibility
3997  * @throws InternalServerErrorException
3998  */
3999 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4000 {
4001         // get data about the api authenticated user
4002         $uri = Item::newURI(intval(BaseApi::getCurrentUserID()));
4003         $owner_record = DBA::selectFirst('contact', [], ['uid' => BaseApi::getCurrentUserID(), 'self' => true]);
4004
4005         $arr = [];
4006         $arr['guid']          = System::createUUID();
4007         $arr['uid']           = intval(BaseApi::getCurrentUserID());
4008         $arr['uri']           = $uri;
4009         $arr['type']          = 'photo';
4010         $arr['wall']          = 1;
4011         $arr['resource-id']   = $hash;
4012         $arr['contact-id']    = $owner_record['id'];
4013         $arr['owner-name']    = $owner_record['name'];
4014         $arr['owner-link']    = $owner_record['url'];
4015         $arr['owner-avatar']  = $owner_record['thumb'];
4016         $arr['author-name']   = $owner_record['name'];
4017         $arr['author-link']   = $owner_record['url'];
4018         $arr['author-avatar'] = $owner_record['thumb'];
4019         $arr['title']         = "";
4020         $arr['allow_cid']     = $allow_cid;
4021         $arr['allow_gid']     = $allow_gid;
4022         $arr['deny_cid']      = $deny_cid;
4023         $arr['deny_gid']      = $deny_gid;
4024         $arr['visible']       = $visibility;
4025         $arr['origin']        = 1;
4026
4027         $typetoext = [
4028                         'image/jpeg' => 'jpg',
4029                         'image/png' => 'png',
4030                         'image/gif' => 'gif'
4031                         ];
4032
4033         // adds link to the thumbnail scale photo
4034         $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4035                                 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4036                                 . '[/url]';
4037
4038         // do the magic for storing the item in the database and trigger the federation to other contacts
4039         Item::insert($arr);
4040 }
4041
4042 /**
4043  *
4044  * @param string $type
4045  * @param int    $scale
4046  * @param string $photo_id
4047  *
4048  * @return array
4049  * @throws BadRequestException
4050  * @throws ForbiddenException
4051  * @throws ImagickException
4052  * @throws InternalServerErrorException
4053  * @throws NotFoundException
4054  * @throws UnauthorizedException
4055  */
4056 function prepare_photo_data($type, $scale, $photo_id)
4057 {
4058         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4059
4060         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4061
4062         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4063         $data_sql = ($scale === false ? "" : "data, ");
4064
4065         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4066         // clients needs to convert this in their way for further processing
4067         $r = DBA::toArray(DBA::p(
4068                 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4069                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4070                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4071                         FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
4072                                    `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4073                                    `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4074                 local_user(),
4075                 $photo_id
4076         ));
4077
4078         $typetoext = [
4079                 'image/jpeg' => 'jpg',
4080                 'image/png' => 'png',
4081                 'image/gif' => 'gif'
4082         ];
4083
4084         // prepare output data for photo
4085         if (DBA::isResult($r)) {
4086                 $data = ['photo' => $r[0]];
4087                 $data['photo']['id'] = $data['photo']['resource-id'];
4088                 if ($scale !== false) {
4089                         $data['photo']['data'] = base64_encode($data['photo']['data']);
4090                 } else {
4091                         unset($data['photo']['datasize']); //needed only with scale param
4092                 }
4093                 if ($type == "xml") {
4094                         $data['photo']['links'] = [];
4095                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4096                                 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4097                                                                                 "scale" => $k,
4098                                                                                 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4099                         }
4100                 } else {
4101                         $data['photo']['link'] = [];
4102                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4103                         $i = 0;
4104                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4105                                 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4106                                 $i++;
4107                         }
4108                 }
4109                 unset($data['photo']['resource-id']);
4110                 unset($data['photo']['minscale']);
4111                 unset($data['photo']['maxscale']);
4112         } else {
4113                 throw new NotFoundException();
4114         }
4115
4116         // retrieve item element for getting activities (like, dislike etc.) related to photo
4117         $condition = ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id];
4118         $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4119         if (!DBA::isResult($item)) {
4120                 throw new NotFoundException('Photo-related item not found.');
4121         }
4122
4123         $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4124
4125         // retrieve comments on photo
4126         $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4127                 $item['parent'], BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT];
4128
4129         $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition);
4130
4131         // prepare output of comments
4132         $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4133         $comments = [];
4134         if ($type == "xml") {
4135                 $k = 0;
4136                 foreach ($commentData as $comment) {
4137                         $comments[$k++ . ":comment"] = $comment;
4138                 }
4139         } else {
4140                 foreach ($commentData as $comment) {
4141                         $comments[] = $comment;
4142                 }
4143         }
4144         $data['photo']['friendica_comments'] = $comments;
4145
4146         // include info if rights on photo and rights on item are mismatching
4147         $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4148                 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4149                 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4150                 $data['photo']['deny_gid'] != $item['deny_gid'];
4151         $data['photo']['rights_mismatch'] = $rights_mismatch;
4152
4153         return $data;
4154 }
4155
4156 /**
4157  * Return an item with announcer data if it had been announced
4158  *
4159  * @param array $item Item array
4160  * @return array Item array with announce data
4161  */
4162 function api_get_announce($item)
4163 {
4164         // Quit if the item already has got a different owner and author
4165         if ($item['owner-id'] != $item['author-id']) {
4166                 return [];
4167         }
4168
4169         // Don't change original or Diaspora posts
4170         if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4171                 return [];
4172         }
4173
4174         // Quit if we do now the original author and it had been a post from a native network
4175         if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4176                 return [];
4177         }
4178
4179         $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4180         $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4181         $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4182         if (!DBA::isResult($announce)) {
4183                 return [];
4184         }
4185
4186         return array_merge($item, $announce);
4187 }
4188
4189 /**
4190  *
4191  * @param array $item
4192  *
4193  * @return array
4194  * @throws Exception
4195  */
4196 function api_in_reply_to($item)
4197 {
4198         $in_reply_to = [];
4199
4200         $in_reply_to['status_id'] = null;
4201         $in_reply_to['user_id'] = null;
4202         $in_reply_to['status_id_str'] = null;
4203         $in_reply_to['user_id_str'] = null;
4204         $in_reply_to['screen_name'] = null;
4205
4206         if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4207                 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4208                 if (DBA::isResult($parent)) {
4209                         $in_reply_to['status_id'] = intval($parent['id']);
4210                 } else {
4211                         $in_reply_to['status_id'] = intval($item['parent']);
4212                 }
4213
4214                 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4215
4216                 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4217                 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4218
4219                 if (DBA::isResult($parent)) {
4220                         $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4221                         $in_reply_to['user_id'] = intval($parent['author-id']);
4222                         $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4223                 }
4224
4225                 // There seems to be situation, where both fields are identical:
4226                 // https://github.com/friendica/friendica/issues/1010
4227                 // This is a bugfix for that.
4228                 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4229                         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']]);
4230                         $in_reply_to['status_id'] = null;
4231                         $in_reply_to['user_id'] = null;
4232                         $in_reply_to['status_id_str'] = null;
4233                         $in_reply_to['user_id_str'] = null;
4234                         $in_reply_to['screen_name'] = null;
4235                 }
4236         }
4237
4238         return $in_reply_to;
4239 }
4240
4241 /**
4242  *
4243  * @param string $text
4244  *
4245  * @return string
4246  * @throws InternalServerErrorException
4247  */
4248 function api_clean_plain_items($text)
4249 {
4250         $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4251
4252         $text = BBCode::cleanPictureLinks($text);
4253         $URLSearchString = "^\[\]";
4254
4255         $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4256
4257         if ($include_entities == "true") {
4258                 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4259         }
4260
4261         // Simplify "attachment" element
4262         $text = BBCode::removeAttachment($text);
4263
4264         return $text;
4265 }
4266
4267 /**
4268  *
4269  * @param array $contacts
4270  *
4271  * @return void
4272  */
4273 function api_best_nickname(&$contacts)
4274 {
4275         $best_contact = [];
4276
4277         if (count($contacts) == 0) {
4278                 return;
4279         }
4280
4281         foreach ($contacts as $contact) {
4282                 if ($contact["network"] == "") {
4283                         $contact["network"] = "dfrn";
4284                         $best_contact = [$contact];
4285                 }
4286         }
4287
4288         if (sizeof($best_contact) == 0) {
4289                 foreach ($contacts as $contact) {
4290                         if ($contact["network"] == "dfrn") {
4291                                 $best_contact = [$contact];
4292                         }
4293                 }
4294         }
4295
4296         if (sizeof($best_contact) == 0) {
4297                 foreach ($contacts as $contact) {
4298                         if ($contact["network"] == "dspr") {
4299                                 $best_contact = [$contact];
4300                         }
4301                 }
4302         }
4303
4304         if (sizeof($best_contact) == 0) {
4305                 foreach ($contacts as $contact) {
4306                         if ($contact["network"] == "stat") {
4307                                 $best_contact = [$contact];
4308                         }
4309                 }
4310         }
4311
4312         if (sizeof($best_contact) == 0) {
4313                 foreach ($contacts as $contact) {
4314                         if ($contact["network"] == "pump") {
4315                                 $best_contact = [$contact];
4316                         }
4317                 }
4318         }
4319
4320         if (sizeof($best_contact) == 0) {
4321                 foreach ($contacts as $contact) {
4322                         if ($contact["network"] == "twit") {
4323                                 $best_contact = [$contact];
4324                         }
4325                 }
4326         }
4327
4328         if (sizeof($best_contact) == 1) {
4329                 $contacts = $best_contact;
4330         } else {
4331                 $contacts = [$contacts[0]];
4332         }
4333 }
4334
4335 /**
4336  * Return all or a specified group of the user with the containing contacts.
4337  *
4338  * @param string $type Return type (atom, rss, xml, json)
4339  *
4340  * @return array|string
4341  * @throws BadRequestException
4342  * @throws ForbiddenException
4343  * @throws ImagickException
4344  * @throws InternalServerErrorException
4345  * @throws UnauthorizedException
4346  */
4347 function api_friendica_group_show($type)
4348 {
4349         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4350
4351         // params
4352         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4353         $gid = $_REQUEST['gid'] ?? 0;
4354         $uid = $user_info['uid'];
4355
4356         // get data of the specified group id or all groups if not specified
4357         if ($gid != 0) {
4358                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
4359
4360                 // error message if specified gid is not in database
4361                 if (!DBA::isResult($groups)) {
4362                         throw new BadRequestException("gid not available");
4363                 }
4364         } else {
4365                 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
4366         }
4367
4368         // loop through all groups and retrieve all members for adding data in the user array
4369         $grps = [];
4370         foreach ($groups as $rr) {
4371                 $members = Contact\Group::getById($rr['id']);
4372                 $users = [];
4373
4374                 if ($type == "xml") {
4375                         $user_element = "users";
4376                         $k = 0;
4377                         foreach ($members as $member) {
4378                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
4379                                 $users[$k++.":user"] = $user;
4380                         }
4381                 } else {
4382                         $user_element = "user";
4383                         foreach ($members as $member) {
4384                                 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
4385                                 $users[] = $user;
4386                         }
4387                 }
4388                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
4389         }
4390         return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
4391 }
4392
4393 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4394
4395 /**
4396  * Delete a group.
4397  *
4398  * @param string $type Return type (atom, rss, xml, json)
4399  *
4400  * @return array|string
4401  * @throws BadRequestException
4402  * @throws ForbiddenException
4403  * @throws ImagickException
4404  * @throws InternalServerErrorException
4405  * @throws UnauthorizedException
4406  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
4407  */
4408 function api_lists_destroy($type)
4409 {
4410         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4411
4412         // params
4413         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4414         $gid = $_REQUEST['list_id'] ?? 0;
4415         $uid = $user_info['uid'];
4416
4417         // error if no gid specified
4418         if ($gid == 0) {
4419                 throw new BadRequestException('gid not specified');
4420         }
4421
4422         // get data of the specified group id
4423         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4424         // error message if specified gid is not in database
4425         if (!$group) {
4426                 throw new BadRequestException('gid not available');
4427         }
4428
4429         if (Group::remove($gid)) {
4430                 $list = [
4431                         'name' => $group['name'],
4432                         'id' => intval($gid),
4433                         'id_str' => (string) $gid,
4434                         'user' => $user_info
4435                 ];
4436
4437                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4438         }
4439 }
4440
4441 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
4442
4443 /**
4444  * Add a new group to the database.
4445  *
4446  * @param  string $name  Group name
4447  * @param  int    $uid   User ID
4448  * @param  array  $users List of users to add to the group
4449  *
4450  * @return array
4451  * @throws BadRequestException
4452  */
4453 function group_create($name, $uid, $users = [])
4454 {
4455         // error if no name specified
4456         if ($name == "") {
4457                 throw new BadRequestException('group name not specified');
4458         }
4459
4460         // error message if specified group name already exists
4461         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
4462                 throw new BadRequestException('group name already exists');
4463         }
4464
4465         // Check if the group needs to be reactivated
4466         if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
4467                 $reactivate_group = true;
4468         }
4469
4470         // create group
4471         $ret = Group::create($uid, $name);
4472         if ($ret) {
4473                 $gid = Group::getIdByName($uid, $name);
4474         } else {
4475                 throw new BadRequestException('other API error');
4476         }
4477
4478         // add members
4479         $erroraddinguser = false;
4480         $errorusers = [];
4481         foreach ($users as $user) {
4482                 $cid = $user['cid'];
4483                 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4484                         Group::addMember($gid, $cid);
4485                 } else {
4486                         $erroraddinguser = true;
4487                         $errorusers[] = $cid;
4488                 }
4489         }
4490
4491         // return success message incl. missing users in array
4492         $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
4493
4494         return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4495 }
4496
4497 /**
4498  * Create the specified group with the posted array of contacts.
4499  *
4500  * @param string $type Return type (atom, rss, xml, json)
4501  *
4502  * @return array|string
4503  * @throws BadRequestException
4504  * @throws ForbiddenException
4505  * @throws ImagickException
4506  * @throws InternalServerErrorException
4507  * @throws UnauthorizedException
4508  */
4509 function api_friendica_group_create($type)
4510 {
4511         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4512
4513         // params
4514         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4515         $name = $_REQUEST['name'] ?? '';
4516         $uid = $user_info['uid'];
4517         $json = json_decode($_POST['json'], true);
4518         $users = $json['user'];
4519
4520         $success = group_create($name, $uid, $users);
4521
4522         return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
4523 }
4524
4525 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4526
4527 /**
4528  * Create a new group.
4529  *
4530  * @param string $type Return type (atom, rss, xml, json)
4531  *
4532  * @return array|string
4533  * @throws BadRequestException
4534  * @throws ForbiddenException
4535  * @throws ImagickException
4536  * @throws InternalServerErrorException
4537  * @throws UnauthorizedException
4538  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
4539  */
4540 function api_lists_create($type)
4541 {
4542         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4543
4544         // params
4545         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4546         $name = $_REQUEST['name'] ?? '';
4547         $uid = $user_info['uid'];
4548
4549         $success = group_create($name, $uid);
4550         if ($success['success']) {
4551                 $grp = [
4552                         'name' => $success['name'],
4553                         'id' => intval($success['gid']),
4554                         'id_str' => (string) $success['gid'],
4555                         'user' => $user_info
4556                 ];
4557
4558                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
4559         }
4560 }
4561
4562 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4563
4564 /**
4565  * Update the specified group with the posted array of contacts.
4566  *
4567  * @param string $type Return type (atom, rss, xml, json)
4568  *
4569  * @return array|string
4570  * @throws BadRequestException
4571  * @throws ForbiddenException
4572  * @throws ImagickException
4573  * @throws InternalServerErrorException
4574  * @throws UnauthorizedException
4575  */
4576 function api_friendica_group_update($type)
4577 {
4578         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4579
4580         // params
4581         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4582         $uid = $user_info['uid'];
4583         $gid = $_REQUEST['gid'] ?? 0;
4584         $name = $_REQUEST['name'] ?? '';
4585         $json = json_decode($_POST['json'], true);
4586         $users = $json['user'];
4587
4588         // error if no name specified
4589         if ($name == "") {
4590                 throw new BadRequestException('group name not specified');
4591         }
4592
4593         // error if no gid specified
4594         if ($gid == "") {
4595                 throw new BadRequestException('gid not specified');
4596         }
4597
4598         // remove members
4599         $members = Contact\Group::getById($gid);
4600         foreach ($members as $member) {
4601                 $cid = $member['id'];
4602                 foreach ($users as $user) {
4603                         $found = ($user['cid'] == $cid ? true : false);
4604                 }
4605                 if (!isset($found) || !$found) {
4606                         $gid = Group::getIdByName($uid, $name);
4607                         Group::removeMember($gid, $cid);
4608                 }
4609         }
4610
4611         // add members
4612         $erroraddinguser = false;
4613         $errorusers = [];
4614         foreach ($users as $user) {
4615                 $cid = $user['cid'];
4616
4617                 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4618                         Group::addMember($gid, $cid);
4619                 } else {
4620                         $erroraddinguser = true;
4621                         $errorusers[] = $cid;
4622                 }
4623         }
4624
4625         // return success message incl. missing users in array
4626         $status = ($erroraddinguser ? "missing user" : "ok");
4627         $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4628         return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
4629 }
4630
4631 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4632
4633 /**
4634  * Update information about a group.
4635  *
4636  * @param string $type Return type (atom, rss, xml, json)
4637  *
4638  * @return array|string
4639  * @throws BadRequestException
4640  * @throws ForbiddenException
4641  * @throws ImagickException
4642  * @throws InternalServerErrorException
4643  * @throws UnauthorizedException
4644  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4645  */
4646 function api_lists_update($type)
4647 {
4648         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4649
4650         // params
4651         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4652         $gid = $_REQUEST['list_id'] ?? 0;
4653         $name = $_REQUEST['name'] ?? '';
4654         $uid = $user_info['uid'];
4655
4656         // error if no gid specified
4657         if ($gid == 0) {
4658                 throw new BadRequestException('gid not specified');
4659         }
4660
4661         // get data of the specified group id
4662         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4663         // error message if specified gid is not in database
4664         if (!$group) {
4665                 throw new BadRequestException('gid not available');
4666         }
4667
4668         if (Group::update($gid, $name)) {
4669                 $list = [
4670                         'name' => $name,
4671                         'id' => intval($gid),
4672                         'id_str' => (string) $gid,
4673                         'user' => $user_info
4674                 ];
4675
4676                 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4677         }
4678 }
4679
4680 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4681
4682 /**
4683  * Set notification as seen and returns associated item (if possible)
4684  *
4685  * POST request with 'id' param as notification id
4686  *
4687  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4688  * @return string|array
4689  * @throws BadRequestException
4690  * @throws ForbiddenException
4691  * @throws ImagickException
4692  * @throws InternalServerErrorException
4693  * @throws UnauthorizedException
4694  */
4695 function api_friendica_notification_seen($type)
4696 {
4697         BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4698
4699         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4700
4701         if (DI::args()->getArgc() !== 4) {
4702                 throw new BadRequestException('Invalid argument count');
4703         }
4704
4705         $id = intval($_REQUEST['id'] ?? 0);
4706
4707         try {
4708                 $Notify = DI::notify()->selectOneById($id);
4709                 if ($Notify->uid !== BaseApi::getCurrentUserID()) {
4710                         throw new NotFoundException();
4711                 }
4712
4713                 if ($Notify->uriId) {
4714                         DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
4715                 }
4716
4717                 $Notify->setSeen();
4718                 DI::notify()->save($Notify);
4719
4720                 if ($Notify->otype === Notification\ObjectType::ITEM) {
4721                         $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $Notify->iid, 'uid' => BaseApi::getCurrentUserID()]);
4722                         if (DBA::isResult($item)) {
4723                                 // we found the item, return it to the user
4724                                 $ret  = api_format_items([$item], $user_info, false, $type);
4725                                 $data = ['status' => $ret];
4726                                 return DI::apiResponse()->formatData('status', $type, $data);
4727                         }
4728                         // the item can't be found, but we set the notification as seen, so we count this as a success
4729                 }
4730
4731                 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
4732         } catch (NotFoundException $e) {
4733                 throw new BadRequestException('Invalid argument', $e);
4734         } catch (Exception $e) {
4735                 throw new InternalServerErrorException('Internal Server exception', $e);
4736         }
4737 }
4738
4739 /// @TODO move to top of file or somewhere better
4740 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4741
4742 /**
4743  * search for direct_messages containing a searchstring through api
4744  *
4745  * @param string $type      Known types are 'atom', 'rss', 'xml' and 'json'
4746  * @param string $box
4747  * @return string|array (success: success=true if found and search_result contains found messages,
4748  *                          success=false if nothing was found, search_result='nothing found',
4749  *                          error: result=error with error message)
4750  * @throws BadRequestException
4751  * @throws ForbiddenException
4752  * @throws ImagickException
4753  * @throws InternalServerErrorException
4754  * @throws UnauthorizedException
4755  */
4756 function api_friendica_direct_messages_search($type, $box = "")
4757 {
4758         BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4759
4760         // params
4761         $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4762         $searchstring = $_REQUEST['searchstring'] ?? '';
4763         $uid = $user_info['uid'];
4764
4765         // error if no searchstring specified
4766         if ($searchstring == "") {
4767                 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
4768                 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
4769         }
4770
4771         // get data for the specified searchstring
4772         $r = DBA::toArray(DBA::p(
4773                 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND `body` LIKE ? ORDER BY `mail`.`id` DESC",
4774                 $uid,
4775                 '%'.$searchstring.'%'
4776         ));
4777
4778         $profile_url = $user_info["url"];
4779
4780         // message if nothing was found
4781         if (!DBA::isResult($r)) {
4782                 $success = ['success' => false, 'search_results' => 'problem with query'];
4783         } elseif (count($r) == 0) {
4784                 $success = ['success' => false, 'search_results' => 'nothing found'];
4785         } else {
4786                 $ret = [];
4787                 foreach ($r as $item) {
4788                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
4789                                 $recipient = $user_info;
4790                                 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4791                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4792                                 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4793                                 $sender = $user_info;
4794                         }
4795
4796                         if (isset($recipient) && isset($sender)) {
4797                                 $ret[] = api_format_messages($item, $recipient, $sender);
4798                         }
4799                 }
4800                 $success = ['success' => true, 'search_results' => $ret];
4801         }
4802
4803         return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
4804 }
4805
4806 /// @TODO move to top of file or somewhere better
4807 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4808
4809 /*
4810  * Number of comments
4811  *
4812  * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
4813  *
4814  * @param object $data [Status, Status]
4815  *
4816  * @return void
4817  */
4818 function bindComments(&$data)
4819 {
4820         if (count($data) == 0) {
4821                 return;
4822         }
4823
4824         $ids = [];
4825         $comments = [];
4826         foreach ($data as $item) {
4827                 $ids[] = $item['id'];
4828         }
4829
4830         $idStr = DBA::escape(implode(', ', $ids));
4831         $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
4832         $items = DBA::p($sql, 0, GRAVITY_COMMENT);
4833         $itemsData = DBA::toArray($items);
4834
4835         foreach ($itemsData as $item) {
4836                 $comments[$item['parent']] = $item['comments'];
4837         }
4838
4839         foreach ($data as $idx => $item) {
4840                 $id = $item['id'];
4841                 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
4842         }
4843 }
4844
4845 /*
4846 @TODO Maybe open to implement?
4847 To.Do:
4848         [pagename] => api/1.1/statuses/lookup.json
4849         [id] => 605138389168451584
4850         [include_cards] => true
4851         [cards_platform] => Android-12
4852         [include_entities] => true
4853         [include_my_retweet] => 1
4854         [include_rts] => 1
4855         [include_reply_count] => true
4856         [include_descendent_reply_count] => true
4857 (?)
4858
4859
4860 Not implemented by now:
4861 statuses/retweets_of_me
4862 friendships/create
4863 friendships/destroy
4864 friendships/exists
4865 friendships/show
4866 account/update_location
4867 account/update_profile_background_image
4868 blocks/create
4869 blocks/destroy
4870 friendica/profile/update
4871 friendica/profile/create
4872 friendica/profile/delete
4873
4874 Not implemented in status.net:
4875 statuses/retweeted_to_me
4876 statuses/retweeted_by_me
4877 direct_messages/destroy
4878 account/end_session
4879 account/update_delivery_device
4880 notifications/follow
4881 notifications/leave
4882 blocks/exists
4883 blocks/blocking
4884 lists
4885 */