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