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