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