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