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