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