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