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