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