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