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