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