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