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