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