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