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