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