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