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