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