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