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