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