]> git.mxchange.org Git - friendica.git/blob - include/api.php
Merge pull request #4327 from MrPetovan/task/3878-move-datetime-to-src
[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/datetime.php';
45 require_once 'include/conversation.php';
46 require_once 'include/html2plain.php';
47 require_once 'mod/share.php';
48 require_once 'mod/item.php';
49 require_once 'include/security.php';
50 require_once 'include/html2bbcode.php';
51 require_once 'mod/wall_upload.php';
52 require_once 'mod/proxy.php';
53
54 define('API_METHOD_ANY', '*');
55 define('API_METHOD_GET', 'GET');
56 define('API_METHOD_POST', 'POST,PUT');
57 define('API_METHOD_DELETE', 'POST,DELETE');
58
59 $API = [];
60 $called_api = null;
61
62 /**
63  * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
64  * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
65  * into a page, and visitors will post something without noticing it).
66  *
67  * @brief Auth API user
68  */
69 function api_user()
70 {
71         if (x($_SESSION, 'allow_api')) {
72                 return local_user();
73         }
74
75         return false;
76 }
77
78 /**
79  * Clients can send 'source' parameter to be show in post metadata
80  * as "sent via <source>".
81  * Some clients doesn't send a source param, we support ones we know
82  * (only Twidere, atm)
83  *
84  * @brief Get source name from API client
85  *
86  * @return string
87  *              Client source name, default to "api" if unset/unknown
88  */
89 function api_source()
90 {
91         if (requestdata('source')) {
92                 return requestdata('source');
93         }
94
95         // Support for known clients that doesn't send a source name
96         if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
97                 return "Twidere";
98         }
99
100         logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
101
102         return "api";
103 }
104
105 /**
106  * @brief Format date for API
107  *
108  * @param string $str Source date, as UTC
109  * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
110  */
111 function api_date($str)
112 {
113         // Wed May 23 06:01:13 +0000 2007
114         return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
115 }
116
117 /**
118  * Register a function to be the endpoint for defined API path.
119  *
120  * @brief Register API endpoint
121  *
122  * @param string $path   API URL path, relative to System::baseUrl()
123  * @param string $func   Function name to call on path request
124  * @param bool   $auth   API need logged user
125  * @param string $method HTTP method reqiured to call this endpoint.
126  *                       One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
127  *                       Default to API_METHOD_ANY
128  */
129 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
130 {
131         global $API;
132
133         $API[$path] = [
134                 'func'   => $func,
135                 'auth'   => $auth,
136                 'method' => $method,
137         ];
138
139         // Workaround for hotot
140         $path = str_replace("api/", "api/1.1/", $path);
141
142         $API[$path] = [
143                 'func'   => $func,
144                 'auth'   => $auth,
145                 'method' => $method,
146         ];
147 }
148
149 /**
150  * Log in user via OAuth1 or Simple HTTP Auth.
151  * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
152  *
153  * @brief Login API user
154  *
155  * @param object $a App
156  * @hook 'authenticate'
157  *              array $addon_auth
158  *                      'username' => username from login form
159  *                      'password' => password from login form
160  *                      'authenticated' => return status,
161  *                      'user_record' => return authenticated user record
162  * @hook 'logged_in'
163  *              array $user     logged user record
164  */
165 function api_login(App $a)
166 {
167         $oauth1 = new FKOAuth1();
168         // login with oauth
169         try {
170                 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
171                 if (!is_null($token)) {
172                         $oauth1->loginUser($token->uid);
173                         Addon::callHooks('logged_in', $a->user);
174                         return;
175                 }
176                 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
177                 var_dump($consumer, $token);
178                 die();
179         } catch (Exception $e) {
180                 logger($e);
181         }
182
183         // workaround for HTTP-auth in CGI mode
184         if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
185                 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
186                 if (strlen($userpass)) {
187                         list($name, $password) = explode(':', $userpass);
188                         $_SERVER['PHP_AUTH_USER'] = $name;
189                         $_SERVER['PHP_AUTH_PW'] = $password;
190                 }
191         }
192
193         if (!x($_SERVER, 'PHP_AUTH_USER')) {
194                 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
195                 header('WWW-Authenticate: Basic realm="Friendica"');
196                 throw new UnauthorizedException("This API requires login");
197         }
198
199         $user = $_SERVER['PHP_AUTH_USER'];
200         $password = $_SERVER['PHP_AUTH_PW'];
201
202         // allow "user@server" login (but ignore 'server' part)
203         $at = strstr($user, "@", true);
204         if ($at) {
205                 $user = $at;
206         }
207
208         // next code from mod/auth.php. needs better solution
209         $record = null;
210
211         $addon_auth = [
212                 'username' => trim($user),
213                 'password' => trim($password),
214                 'authenticated' => 0,
215                 'user_record' => null,
216         ];
217
218         /*
219         * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
220         * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
221         * and later addons should not interfere with an earlier one that succeeded.
222         */
223         Addon::callHooks('authenticate', $addon_auth);
224
225         if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
226                 $record = $addon_auth['user_record'];
227         } else {
228                 $user_id = User::authenticate(trim($user), trim($password));
229                 if ($user_id) {
230                         $record = dba::selectFirst('user', [], ['uid' => $user_id]);
231                 }
232         }
233
234         if (!DBM::is_result($record)) {
235                 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
236                 header('WWW-Authenticate: Basic realm="Friendica"');
237                 //header('HTTP/1.0 401 Unauthorized');
238                 //die('This api requires login');
239                 throw new UnauthorizedException("This API requires login");
240         }
241
242         authenticate_success($record);
243
244         $_SESSION["allow_api"] = true;
245
246         Addon::callHooks('logged_in', $a->user);
247 }
248
249 /**
250  * API endpoints can define which HTTP method to accept when called.
251  * This function check the current HTTP method agains endpoint
252  * registered method.
253  *
254  * @brief Check HTTP method of called API
255  *
256  * @param string $method Required methods, uppercase, separated by comma
257  * @return bool
258  */
259 function api_check_method($method)
260 {
261         if ($method == "*") {
262                 return true;
263         }
264         return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
265 }
266
267 /**
268  * Authenticate user, call registered API function, set HTTP headers
269  *
270  * @brief Main API entry point
271  *
272  * @param object $a App
273  * @return string API call result
274  */
275 function api_call(App $a)
276 {
277         global $API, $called_api;
278
279         $type = "json";
280         if (strpos($a->query_string, ".xml") > 0) {
281                 $type = "xml";
282         }
283         if (strpos($a->query_string, ".json") > 0) {
284                 $type = "json";
285         }
286         if (strpos($a->query_string, ".rss") > 0) {
287                 $type = "rss";
288         }
289         if (strpos($a->query_string, ".atom") > 0) {
290                 $type = "atom";
291         }
292
293         try {
294                 foreach ($API as $p => $info) {
295                         if (strpos($a->query_string, $p) === 0) {
296                                 if (!api_check_method($info['method'])) {
297                                         throw new MethodNotAllowedException();
298                                 }
299
300                                 $called_api = explode("/", $p);
301                                 //unset($_SERVER['PHP_AUTH_USER']);
302
303                                 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
304                                 if ($info['auth'] === true && api_user() === false) {
305                                         api_login($a);
306                                 }
307
308                                 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
309                                 logger('API parameters: ' . print_r($_REQUEST, true));
310
311                                 $stamp =  microtime(true);
312                                 $return = call_user_func($info['func'], $type);
313                                 $duration = (float) (microtime(true) - $stamp);
314                                 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
315
316                                 if (Config::get("system", "profiler")) {
317                                         $duration = microtime(true)-$a->performance["start"];
318
319                                         /// @TODO round() really everywhere?
320                                         logger(
321                                                 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
322                                                         "Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
323                                                         round($a->performance["database"] - $a->performance["database_write"], 3),
324                                                         round($a->performance["database_write"], 3),
325                                                         round($a->performance["network"], 2),
326                                                         round($a->performance["file"], 2),
327                                                         round($duration - ($a->performance["database"] + $a->performance["network"]     + $a->performance["file"]), 2),
328                                                         round($duration, 2)
329                                                 ),
330                                                 LOGGER_DEBUG
331                                         );
332
333                                         if (Config::get("rendertime", "callstack")) {
334                                                 $o = "Database Read:\n";
335                                                 foreach ($a->callstack["database"] as $func => $time) {
336                                                         $time = round($time, 3);
337                                                         if ($time > 0) {
338                                                                 $o .= $func . ": " . $time . "\n";
339                                                         }
340                                                 }
341                                                 $o .= "\nDatabase Write:\n";
342                                                 foreach ($a->callstack["database_write"] as $func => $time) {
343                                                         $time = round($time, 3);
344                                                         if ($time > 0) {
345                                                                 $o .= $func . ": " . $time . "\n";
346                                                         }
347                                                 }
348
349                                                 $o .= "\nNetwork:\n";
350                                                 foreach ($a->callstack["network"] as $func => $time) {
351                                                         $time = round($time, 3);
352                                                         if ($time > 0) {
353                                                                 $o .= $func . ": " . $time . "\n";
354                                                         }
355                                                 }
356                                                 logger($o, LOGGER_DEBUG);
357                                         }
358                                 }
359
360                                 if (false === $return) {
361                                         /*
362                                                 * api function returned false withour throw an
363                                                 * exception. This should not happend, throw a 500
364                                                 */
365                                         throw new InternalServerErrorException();
366                                 }
367
368                                 switch ($type) {
369                                         case "xml":
370                                                 header("Content-Type: text/xml");
371                                                 break;
372                                         case "json":
373                                                 header("Content-Type: application/json");
374                                                 foreach ($return as $rr) {
375                                                         $json = json_encode($rr);
376                                                 }
377                                                 if (x($_GET, 'callback')) {
378                                                         $json = $_GET['callback'] . "(" . $json . ")";
379                                                 }
380                                                 $return = $json;
381                                                 break;
382                                         case "rss":
383                                                 header("Content-Type: application/rss+xml");
384                                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
385                                                 break;
386                                         case "atom":
387                                                 header("Content-Type: application/atom+xml");
388                                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
389                                                 break;
390                                 }
391                                 return $return;
392                         }
393                 }
394
395                 logger('API call not implemented: ' . $a->query_string);
396                 throw new NotImplementedException();
397         } catch (HTTPException $e) {
398                 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
399                 return api_error($type, $e);
400         }
401 }
402
403 /**
404  * @brief Format API error string
405  *
406  * @param string $type Return type (xml, json, rss, as)
407  * @param object $e    HTTPException Error object
408  * @return string error message formatted as $type
409  */
410 function api_error($type, $e)
411 {
412         $a = get_app();
413
414         $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
415         /// @TODO:  https://dev.twitter.com/overview/api/response-codes
416
417         $error = ["error" => $error,
418                         "code" => $e->httpcode . " " . $e->httpdesc,
419                         "request" => $a->query_string];
420
421         $return = api_format_data('status', $type, ['status' => $error]);
422
423         switch ($type) {
424                 case "xml":
425                         header("Content-Type: text/xml");
426                         break;
427                 case "json":
428                         header("Content-Type: application/json");
429                         $return = json_encode($return);
430                         break;
431                 case "rss":
432                         header("Content-Type: application/rss+xml");
433                         break;
434                 case "atom":
435                         header("Content-Type: application/atom+xml");
436                         break;
437         }
438
439         return $return;
440 }
441
442 /**
443  * @brief Set values for RSS template
444  *
445  * @param App $a
446  * @param array $arr       Array to be passed to template
447  * @param array $user_info User info
448  * @return array
449  * @todo find proper type-hints
450  */
451 function api_rss_extra(App $a, $arr, $user_info)
452 {
453         if (is_null($user_info)) {
454                 $user_info = api_get_user($a);
455         }
456
457         $arr['$user'] = $user_info;
458         $arr['$rss'] = [
459                 'alternate'    => $user_info['url'],
460                 'self'         => System::baseUrl() . "/" . $a->query_string,
461                 'base'         => System::baseUrl(),
462                 'updated'      => api_date(null),
463                 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
464                 'language'     => $user_info['language'],
465                 'logo'         => System::baseUrl() . "/images/friendica-32.png",
466         ];
467
468         return $arr;
469 }
470
471
472 /**
473  * @brief Unique contact to contact url.
474  *
475  * @param int $id Contact id
476  * @return bool|string
477  *              Contact url or False if contact id is unknown
478  */
479 function api_unique_id_to_nurl($id)
480 {
481         $r = dba::selectFirst('contact', ['nurl'], ['uid' => 0, 'id' => $id]);
482
483         if (DBM::is_result($r)) {
484                 return $r["nurl"];
485         } else {
486                 return false;
487         }
488 }
489
490 /**
491  * @brief Get user info array.
492  *
493  * @param object     $a          App
494  * @param int|string $contact_id Contact ID or URL
495  */
496 function api_get_user(App $a, $contact_id = null)
497 {
498         global $called_api;
499
500         $user = null;
501         $extra_query = "";
502         $url = "";
503
504         logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
505
506         // Searching for contact URL
507         if (!is_null($contact_id) && (intval($contact_id) == 0)) {
508                 $user = dbesc(normalise_link($contact_id));
509                 $url = $user;
510                 $extra_query = "AND `contact`.`nurl` = '%s' ";
511                 if (api_user() !== false) {
512                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
513                 }
514         }
515
516         // Searching for contact id with uid = 0
517         if (!is_null($contact_id) && (intval($contact_id) != 0)) {
518                 $user = dbesc(api_unique_id_to_nurl($contact_id));
519
520                 if ($user == "") {
521                         throw new BadRequestException("User not found.");
522                 }
523
524                 $url = $user;
525                 $extra_query = "AND `contact`.`nurl` = '%s' ";
526                 if (api_user() !== false) {
527                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
528                 }
529         }
530
531         if (is_null($user) && x($_GET, 'user_id')) {
532                 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
533
534                 if ($user == "") {
535                         throw new BadRequestException("User not found.");
536                 }
537
538                 $url = $user;
539                 $extra_query = "AND `contact`.`nurl` = '%s' ";
540                 if (api_user() !== false) {
541                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
542                 }
543         }
544         if (is_null($user) && x($_GET, 'screen_name')) {
545                 $user = dbesc($_GET['screen_name']);
546                 $extra_query = "AND `contact`.`nick` = '%s' ";
547                 if (api_user() !== false) {
548                         $extra_query .= "AND `contact`.`uid`=".intval(api_user());
549                 }
550         }
551
552         if (is_null($user) && x($_GET, 'profileurl')) {
553                 $user = dbesc(normalise_link($_GET['profileurl']));
554                 $extra_query = "AND `contact`.`nurl` = '%s' ";
555                 if (api_user() !== false) {
556                         $extra_query .= "AND `contact`.`uid`=".intval(api_user());
557                 }
558         }
559
560         if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
561                 $argid = count($called_api);
562                 list($user, $null) = explode(".", $a->argv[$argid]);
563                 if (is_numeric($user)) {
564                         $user = dbesc(api_unique_id_to_nurl($user));
565
566                         if ($user == "") {
567                                 return false;
568                         }
569
570                         $url = $user;
571                         $extra_query = "AND `contact`.`nurl` = '%s' ";
572                         if (api_user() !== false) {
573                                 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
574                         }
575                 } else {
576                         $user = dbesc($user);
577                         $extra_query = "AND `contact`.`nick` = '%s' ";
578                         if (api_user() !== false) {
579                                 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
580                         }
581                 }
582         }
583
584         logger("api_get_user: user ".$user, LOGGER_DEBUG);
585
586         if (!$user) {
587                 if (api_user() === false) {
588                         api_login($a);
589                         return false;
590                 } else {
591                         $user = $_SESSION['uid'];
592                         $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
593                 }
594         }
595
596         logger('api_user: ' . $extra_query . ', user: ' . $user);
597
598         // user info
599         $uinfo = q(
600                 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
601                         WHERE 1
602                 $extra_query",
603                 $user
604         );
605
606         // Selecting the id by priority, friendica first
607         api_best_nickname($uinfo);
608
609         // if the contact wasn't found, fetch it from the contacts with uid = 0
610         if (!DBM::is_result($uinfo)) {
611                 $r = [];
612
613                 if ($url != "") {
614                         $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
615                 }
616
617                 if (DBM::is_result($r)) {
618                         $network_name = ContactSelector::networkToName($r[0]['network'], $r[0]['url']);
619
620                         // If no nick where given, extract it from the address
621                         if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
622                                 $r[0]['nick'] = api_get_nick($r[0]["url"]);
623                         }
624
625                         $ret = [
626                                 'id' => $r[0]["id"],
627                                 'id_str' => (string) $r[0]["id"],
628                                 'name' => $r[0]["name"],
629                                 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
630                                 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
631                                 'description' => $r[0]["about"],
632                                 'profile_image_url' => $r[0]["micro"],
633                                 'profile_image_url_https' => $r[0]["micro"],
634                                 'url' => $r[0]["url"],
635                                 'protected' => false,
636                                 'followers_count' => 0,
637                                 'friends_count' => 0,
638                                 'listed_count' => 0,
639                                 'created_at' => api_date($r[0]["created"]),
640                                 'favourites_count' => 0,
641                                 'utc_offset' => 0,
642                                 'time_zone' => 'UTC',
643                                 'geo_enabled' => false,
644                                 'verified' => false,
645                                 'statuses_count' => 0,
646                                 'lang' => '',
647                                 'contributors_enabled' => false,
648                                 'is_translator' => false,
649                                 'is_translation_enabled' => false,
650                                 'following' => false,
651                                 'follow_request_sent' => false,
652                                 'statusnet_blocking' => false,
653                                 'notifications' => false,
654                                 'statusnet_profile_url' => $r[0]["url"],
655                                 'uid' => 0,
656                                 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
657                                 'self' => 0,
658                                 'network' => $r[0]["network"],
659                         ];
660
661                         return $ret;
662                 } else {
663                         throw new BadRequestException("User not found.");
664                 }
665         }
666
667         if ($uinfo[0]['self']) {
668                 if ($uinfo[0]['network'] == "") {
669                         $uinfo[0]['network'] = NETWORK_DFRN;
670                 }
671
672                 $usr = q(
673                         "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
674                         intval(api_user())
675                 );
676                 $profile = q(
677                         "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
678                         intval(api_user())
679                 );
680
681                 /// @TODO old-lost code? (twice)
682                 // Counting is deactivated by now, due to performance issues
683                 // count public wall messages
684                 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
685                 //              intval($uinfo[0]['uid'])
686                 //);
687                 //$countitms = $r[0]['count'];
688                 $countitms = 0;
689         } else {
690                 // Counting is deactivated by now, due to performance issues
691                 //$r = q("SELECT count(*) as `count` FROM `item`
692                 //              WHERE  `contact-id` = %d",
693                 //              intval($uinfo[0]['id'])
694                 //);
695                 //$countitms = $r[0]['count'];
696                 $countitms = 0;
697         }
698
699                 /// @TODO old-lost code? (twice)
700                 /*
701                 // Counting is deactivated by now, due to performance issues
702                 // count friends
703                 $r = q("SELECT count(*) as `count` FROM `contact`
704                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
705                                 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
706                                 intval($uinfo[0]['uid']),
707                                 intval(CONTACT_IS_SHARING),
708                                 intval(CONTACT_IS_FRIEND)
709                 );
710                 $countfriends = $r[0]['count'];
711
712                 $r = q("SELECT count(*) as `count` FROM `contact`
713                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
714                                 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
715                                 intval($uinfo[0]['uid']),
716                                 intval(CONTACT_IS_FOLLOWER),
717                                 intval(CONTACT_IS_FRIEND)
718                 );
719                 $countfollowers = $r[0]['count'];
720
721                 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
722                         intval($uinfo[0]['uid'])
723                 );
724                 $starred = $r[0]['count'];
725
726
727                 if (! $uinfo[0]['self']) {
728                         $countfriends = 0;
729                         $countfollowers = 0;
730                         $starred = 0;
731                 }
732                 */
733         $countfriends = 0;
734         $countfollowers = 0;
735         $starred = 0;
736
737         // Add a nick if it isn't present there
738         if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
739                 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
740         }
741
742         $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
743
744         $pcontact_id  = Contact::getIdForURL($uinfo[0]['url'], 0, true);
745
746         if (!empty($profile[0]['about'])) {
747                 $description = $profile[0]['about'];
748         } else {
749                 $description = $uinfo[0]["about"];
750         }
751
752         if (!empty($usr[0]['default-location'])) {
753                 $location = $usr[0]['default-location'];
754         } elseif (!empty($uinfo[0]["location"])) {
755                 $location = $uinfo[0]["location"];
756         } else {
757                 $location = $network_name;
758         }
759
760         $ret = [
761                 'id' => intval($pcontact_id),
762                 'id_str' => (string) intval($pcontact_id),
763                 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
764                 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
765                 'location' => $location,
766                 'description' => $description,
767                 'profile_image_url' => $uinfo[0]['micro'],
768                 'profile_image_url_https' => $uinfo[0]['micro'],
769                 'url' => $uinfo[0]['url'],
770                 'protected' => false,
771                 'followers_count' => intval($countfollowers),
772                 'friends_count' => intval($countfriends),
773                 'listed_count' => 0,
774                 'created_at' => api_date($uinfo[0]['created']),
775                 'favourites_count' => intval($starred),
776                 'utc_offset' => "0",
777                 'time_zone' => 'UTC',
778                 'geo_enabled' => false,
779                 'verified' => true,
780                 'statuses_count' => intval($countitms),
781                 'lang' => '',
782                 'contributors_enabled' => false,
783                 'is_translator' => false,
784                 'is_translation_enabled' => false,
785                 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
786                 'follow_request_sent' => false,
787                 'statusnet_blocking' => false,
788                 'notifications' => false,
789                 /// @TODO old way?
790                 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
791                 'statusnet_profile_url' => $uinfo[0]['url'],
792                 'uid' => intval($uinfo[0]['uid']),
793                 'cid' => intval($uinfo[0]['cid']),
794                 'self' => $uinfo[0]['self'],
795                 'network' => $uinfo[0]['network'],
796         ];
797
798         // If this is a local user and it uses Frio, we can get its color preferences.
799         if ($ret['self']) {
800                 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
801                 if ($theme_info['theme'] === 'frio') {
802                         $schema = PConfig::get($ret['uid'], 'frio', 'schema');
803                         if ($schema && ($schema != '---')) {
804                                 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
805                                         $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
806                                         require_once $schemefile;
807                                 }
808                         } else {
809                                 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
810                                 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
811                                 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
812                         }
813                         if (!$nav_bg) {
814                                 $nav_bg = "#708fa0";
815                         }
816                         if (!$link_color) {
817                                 $link_color = "#6fdbe8";
818                         }
819                         if (!$bgcolor) {
820                                 $bgcolor = "#ededed";
821                         }
822
823                         $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
824                         $ret['profile_link_color'] = str_replace('#', '', $link_color);
825                         $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
826                 }
827         }
828
829         return $ret;
830 }
831
832 /**
833  * @brief return api-formatted array for item's author and owner
834  *
835  * @param object $a    App
836  * @param array  $item item from db
837  * @return array(array:author, array:owner)
838  */
839 function api_item_get_user(App $a, $item)
840 {
841         $status_user = api_get_user($a, $item["author-link"]);
842
843         $status_user["protected"] = (($item["allow_cid"] != "") ||
844                                         ($item["allow_gid"] != "") ||
845                                         ($item["deny_cid"] != "") ||
846                                         ($item["deny_gid"] != "") ||
847                                         $item["private"]);
848
849         if ($item['thr-parent'] == $item['uri']) {
850                 $owner_user = api_get_user($a, $item["owner-link"]);
851         } else {
852                 $owner_user = $status_user;
853         }
854
855         return ([$status_user, $owner_user]);
856 }
857
858 /**
859  * @brief walks recursively through an array with the possibility to change value and key
860  *
861  * @param array  $array    The array to walk through
862  * @param string $callback The callback function
863  *
864  * @return array the transformed array
865  */
866 function api_walk_recursive(array &$array, callable $callback)
867 {
868         $new_array = [];
869
870         foreach ($array as $k => $v) {
871                 if (is_array($v)) {
872                         if ($callback($v, $k)) {
873                                 $new_array[$k] = api_walk_recursive($v, $callback);
874                         }
875                 } else {
876                         if ($callback($v, $k)) {
877                                 $new_array[$k] = $v;
878                         }
879                 }
880         }
881         $array = $new_array;
882
883         return $array;
884 }
885
886 /**
887  * @brief Callback function to transform the array in an array that can be transformed in a XML file
888  *
889  * @param mixed  $item Array item value
890  * @param string $key  Array key
891  *
892  * @return boolean Should the array item be deleted?
893  */
894 function api_reformat_xml(&$item, &$key)
895 {
896         if (is_bool($item)) {
897                 $item = ($item ? "true" : "false");
898         }
899
900         if (substr($key, 0, 10) == "statusnet_") {
901                 $key = "statusnet:".substr($key, 10);
902         } elseif (substr($key, 0, 10) == "friendica_") {
903                 $key = "friendica:".substr($key, 10);
904         }
905         /// @TODO old-lost code?
906         //else
907         //      $key = "default:".$key;
908
909         return true;
910 }
911
912 /**
913  * @brief Creates the XML from a JSON style array
914  *
915  * @param array  $data         JSON style array
916  * @param string $root_element Name of the root element
917  *
918  * @return string The XML data
919  */
920 function api_create_xml($data, $root_element)
921 {
922         $childname = key($data);
923         $data2 = array_pop($data);
924         $key = key($data2);
925
926         $namespaces = ["" => "http://api.twitter.com",
927                                 "statusnet" => "http://status.net/schema/api/1/",
928                                 "friendica" => "http://friendi.ca/schema/api/1/",
929                                 "georss" => "http://www.georss.org/georss"];
930
931         /// @todo Auto detection of needed namespaces
932         if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
933                 $namespaces = [];
934         }
935
936         if (is_array($data2)) {
937                 api_walk_recursive($data2, "api_reformat_xml");
938         }
939
940         if ($key == "0") {
941                 $data4 = [];
942                 $i = 1;
943
944                 foreach ($data2 as $item) {
945                         $data4[$i++.":".$childname] = $item;
946                 }
947
948                 $data2 = $data4;
949         }
950
951         $data3 = [$root_element => $data2];
952
953         $ret = XML::fromArray($data3, $xml, false, $namespaces);
954         return $ret;
955 }
956
957 /**
958  * @brief Formats the data according to the data type
959  *
960  * @param string $root_element Name of the root element
961  * @param string $type         Return type (atom, rss, xml, json)
962  * @param array  $data         JSON style array
963  *
964  * @return (string|object|array) XML data or JSON data
965  */
966 function api_format_data($root_element, $type, $data)
967 {
968         switch ($type) {
969                 case "atom":
970                 case "rss":
971                 case "xml":
972                         $ret = api_create_xml($data, $root_element);
973                         break;
974                 case "json":
975                         $ret = $data;
976                         break;
977         }
978
979         return $ret;
980 }
981
982 /**
983  * TWITTER API
984  */
985
986 /**
987  * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
988  * returns a 401 status code and an error message if not.
989  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
990  *
991  * @param string $type Return type (atom, rss, xml, json)
992  */
993 function api_account_verify_credentials($type)
994 {
995
996         $a = get_app();
997
998         if (api_user() === false) {
999                 throw new ForbiddenException();
1000         }
1001
1002         unset($_REQUEST["user_id"]);
1003         unset($_GET["user_id"]);
1004
1005         unset($_REQUEST["screen_name"]);
1006         unset($_GET["screen_name"]);
1007
1008         $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1009
1010         $user_info = api_get_user($a);
1011
1012         // "verified" isn't used here in the standard
1013         unset($user_info["verified"]);
1014
1015         // - Adding last status
1016         if (!$skip_status) {
1017                 $user_info["status"] = api_status_show("raw");
1018                 if (!count($user_info["status"])) {
1019                         unset($user_info["status"]);
1020                 } else {
1021                         unset($user_info["status"]["user"]);
1022                 }
1023         }
1024
1025         // "uid" and "self" are only needed for some internal stuff, so remove it from here
1026         unset($user_info["uid"]);
1027         unset($user_info["self"]);
1028
1029         return api_format_data("user", $type, ['user' => $user_info]);
1030 }
1031
1032 /// @TODO move to top of file or somewhere better
1033 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1034
1035 /**
1036  * Get data from $_POST or $_GET
1037  *
1038  * @param string $k
1039  */
1040 function requestdata($k)
1041 {
1042         if (x($_POST, $k)) {
1043                 return $_POST[$k];
1044         }
1045         if (x($_GET, $k)) {
1046                 return $_GET[$k];
1047         }
1048         return null;
1049 }
1050
1051 /**
1052  * Waitman Gobble Mod
1053  *
1054  * @param string $type Return type (atom, rss, xml, json)
1055  *
1056  * @return array|string
1057  */
1058 function api_statuses_mediap($type)
1059 {
1060         $a = get_app();
1061
1062         if (api_user() === false) {
1063                 logger('api_statuses_update: no user');
1064                 throw new ForbiddenException();
1065         }
1066         $user_info = api_get_user($a);
1067
1068         $_REQUEST['type'] = 'wall';
1069         $_REQUEST['profile_uid'] = api_user();
1070         $_REQUEST['api_source'] = true;
1071         $txt = requestdata('status');
1072         /// @TODO old-lost code?
1073         //$txt = urldecode(requestdata('status'));
1074
1075         if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1076                 $txt = html2bb_video($txt);
1077                 $config = HTMLPurifier_Config::createDefault();
1078                 $config->set('Cache.DefinitionImpl', null);
1079                 $purifier = new HTMLPurifier($config);
1080                 $txt = $purifier->purify($txt);
1081         }
1082         $txt = html2bbcode($txt);
1083
1084         $a->argv[1]=$user_info['screen_name']; //should be set to username?
1085
1086         // tell wall_upload function to return img info instead of echo
1087         $_REQUEST['hush'] = 'yeah';
1088         $bebop = wall_upload_post($a);
1089
1090         // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1091         $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1092         item_post($a);
1093
1094         // this should output the last post (the one we just posted).
1095         return api_status_show($type);
1096 }
1097
1098 /// @TODO move this to top of file or somewhere better!
1099 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1100
1101 /**
1102  * Updates the user’s current status.
1103  *
1104  * @param string $type Return type (atom, rss, xml, json)
1105  *
1106  * @return array|string
1107  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1108  */
1109 function api_statuses_update($type)
1110 {
1111
1112         $a = get_app();
1113
1114         if (api_user() === false) {
1115                 logger('api_statuses_update: no user');
1116                 throw new ForbiddenException();
1117         }
1118
1119         api_get_user($a);
1120
1121         // convert $_POST array items to the form we use for web posts.
1122         if (requestdata('htmlstatus')) {
1123                 $txt = requestdata('htmlstatus');
1124                 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1125                         $txt = html2bb_video($txt);
1126
1127                         $config = HTMLPurifier_Config::createDefault();
1128                         $config->set('Cache.DefinitionImpl', null);
1129
1130                         $purifier = new HTMLPurifier($config);
1131                         $txt = $purifier->purify($txt);
1132
1133                         $_REQUEST['body'] = html2bbcode($txt);
1134                 }
1135         } else {
1136                 $_REQUEST['body'] = requestdata('status');
1137         }
1138
1139         $_REQUEST['title'] = requestdata('title');
1140
1141         $parent = requestdata('in_reply_to_status_id');
1142
1143         // Twidere sends "-1" if it is no reply ...
1144         if ($parent == -1) {
1145                 $parent = "";
1146         }
1147
1148         if (ctype_digit($parent)) {
1149                 $_REQUEST['parent'] = $parent;
1150         } else {
1151                 $_REQUEST['parent_uri'] = $parent;
1152         }
1153
1154         if (requestdata('lat') && requestdata('long')) {
1155                 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1156         }
1157         $_REQUEST['profile_uid'] = api_user();
1158
1159         if ($parent) {
1160                 $_REQUEST['type'] = 'net-comment';
1161         } else {
1162                 // Check for throttling (maximum posts per day, week and month)
1163                 $throttle_day = Config::get('system', 'throttle_limit_day');
1164                 if ($throttle_day > 0) {
1165                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1166
1167                         $r = q(
1168                                 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1169                                 AND `created` > '%s' AND `id` = `parent`",
1170                                 intval(api_user()),
1171                                 dbesc($datefrom)
1172                         );
1173
1174                         if (DBM::is_result($r)) {
1175                                 $posts_day = $r[0]["posts_day"];
1176                         } else {
1177                                 $posts_day = 0;
1178                         }
1179
1180                         if ($posts_day > $throttle_day) {
1181                                 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1182                                 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1183                                 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));
1184                         }
1185                 }
1186
1187                 $throttle_week = Config::get('system', 'throttle_limit_week');
1188                 if ($throttle_week > 0) {
1189                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1190
1191                         $r = q(
1192                                 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1193                                 AND `created` > '%s' AND `id` = `parent`",
1194                                 intval(api_user()),
1195                                 dbesc($datefrom)
1196                         );
1197
1198                         if (DBM::is_result($r)) {
1199                                 $posts_week = $r[0]["posts_week"];
1200                         } else {
1201                                 $posts_week = 0;
1202                         }
1203
1204                         if ($posts_week > $throttle_week) {
1205                                 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1206                                 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1207                                 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));
1208                         }
1209                 }
1210
1211                 $throttle_month = Config::get('system', 'throttle_limit_month');
1212                 if ($throttle_month > 0) {
1213                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1214
1215                         $r = q(
1216                                 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1217                                 AND `created` > '%s' AND `id` = `parent`",
1218                                 intval(api_user()),
1219                                 dbesc($datefrom)
1220                         );
1221
1222                         if (DBM::is_result($r)) {
1223                                 $posts_month = $r[0]["posts_month"];
1224                         } else {
1225                                 $posts_month = 0;
1226                         }
1227
1228                         if ($posts_month > $throttle_month) {
1229                                 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1230                                 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1231                                 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));
1232                         }
1233                 }
1234
1235                 $_REQUEST['type'] = 'wall';
1236         }
1237
1238         if (x($_FILES, 'media')) {
1239                 // upload the image if we have one
1240                 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1241                 $media = wall_upload_post($a);
1242                 if (strlen($media) > 0) {
1243                         $_REQUEST['body'] .= "\n\n" . $media;
1244                 }
1245         }
1246
1247         // To-Do: Multiple IDs
1248         if (requestdata('media_ids')) {
1249                 $r = q(
1250                         "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",
1251                         intval(requestdata('media_ids')),
1252                         api_user()
1253                 );
1254                 if (DBM::is_result($r)) {
1255                         $phototypes = Image::supportedTypes();
1256                         $ext = $phototypes[$r[0]['type']];
1257                         $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1258                         $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1259                 }
1260         }
1261
1262         // set this so that the item_post() function is quiet and doesn't redirect or emit json
1263
1264         $_REQUEST['api_source'] = true;
1265
1266         if (!x($_REQUEST, "source")) {
1267                 $_REQUEST["source"] = api_source();
1268         }
1269
1270         // call out normal post function
1271         item_post($a);
1272
1273         // this should output the last post (the one we just posted).
1274         return api_status_show($type);
1275 }
1276
1277 /// @TODO move to top of file or somewhere better
1278 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1279 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1280
1281 /**
1282  * Uploads an image to Friendica.
1283  *
1284  * @return array
1285  * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1286  */
1287 function api_media_upload()
1288 {
1289         $a = get_app();
1290
1291         if (api_user() === false) {
1292                 logger('no user');
1293                 throw new ForbiddenException();
1294         }
1295
1296         api_get_user($a);
1297
1298         if (!x($_FILES, 'media')) {
1299                 // Output error
1300                 throw new BadRequestException("No media.");
1301         }
1302
1303         $media = wall_upload_post($a, false);
1304         if (!$media) {
1305                 // Output error
1306                 throw new InternalServerErrorException();
1307         }
1308
1309         $returndata = [];
1310         $returndata["media_id"] = $media["id"];
1311         $returndata["media_id_string"] = (string)$media["id"];
1312         $returndata["size"] = $media["size"];
1313         $returndata["image"] = ["w" => $media["width"],
1314                                         "h" => $media["height"],
1315                                         "image_type" => $media["type"]];
1316
1317         logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1318
1319         return ["media" => $returndata];
1320 }
1321
1322 /// @TODO move to top of file or somewhere better
1323 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1324
1325 /**
1326  *
1327  * @param string $type Return type (atom, rss, xml, json)
1328  *
1329  * @return array|string
1330  */
1331 function api_status_show($type)
1332 {
1333         $a = get_app();
1334
1335         $user_info = api_get_user($a);
1336
1337         logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1338
1339         if ($type == "raw") {
1340                 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1341         } else {
1342                 $privacy_sql = "";
1343         }
1344
1345         // get last public wall message
1346         $lastwall = q(
1347                 "SELECT `item`.*
1348                         FROM `item`
1349                         WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1350                                 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1351                                 AND `item`.`type` != 'activity' $privacy_sql
1352                         ORDER BY `item`.`id` DESC
1353                         LIMIT 1",
1354                 intval($user_info['cid']),
1355                 intval(api_user()),
1356                 dbesc($user_info['url']),
1357                 dbesc(normalise_link($user_info['url'])),
1358                 dbesc($user_info['url']),
1359                 dbesc(normalise_link($user_info['url']))
1360         );
1361
1362         if (DBM::is_result($lastwall)) {
1363                 $lastwall = $lastwall[0];
1364
1365                 $in_reply_to = api_in_reply_to($lastwall);
1366
1367                 $converted = api_convert_item($lastwall);
1368
1369                 if ($type == "xml") {
1370                         $geo = "georss:point";
1371                 } else {
1372                         $geo = "geo";
1373                 }
1374
1375                 $status_info = [
1376                         'created_at' => api_date($lastwall['created']),
1377                         'id' => intval($lastwall['id']),
1378                         'id_str' => (string) $lastwall['id'],
1379                         'text' => $converted["text"],
1380                         'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1381                         'truncated' => false,
1382                         'in_reply_to_status_id' => $in_reply_to['status_id'],
1383                         'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1384                         'in_reply_to_user_id' => $in_reply_to['user_id'],
1385                         'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1386                         'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1387                         'user' => $user_info,
1388                         $geo => null,
1389                         'coordinates' => "",
1390                         'place' => "",
1391                         'contributors' => "",
1392                         'is_quote_status' => false,
1393                         'retweet_count' => 0,
1394                         'favorite_count' => 0,
1395                         'favorited' => $lastwall['starred'] ? true : false,
1396                         'retweeted' => false,
1397                         'possibly_sensitive' => false,
1398                         'lang' => "",
1399                         'statusnet_html' => $converted["html"],
1400                         'statusnet_conversation_id' => $lastwall['parent'],
1401                         'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1402                 ];
1403
1404                 if (count($converted["attachments"]) > 0) {
1405                         $status_info["attachments"] = $converted["attachments"];
1406                 }
1407
1408                 if (count($converted["entities"]) > 0) {
1409                         $status_info["entities"] = $converted["entities"];
1410                 }
1411
1412                 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1413                         $status_info["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1414                 } elseif (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1415                         $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['item_network'], $user_info['url']).')');
1416                 }
1417
1418                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1419                 unset($status_info["user"]["uid"]);
1420                 unset($status_info["user"]["self"]);
1421         }
1422
1423         logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1424
1425         if ($type == "raw") {
1426                 return $status_info;
1427         }
1428
1429         return api_format_data("statuses", $type, ['status' => $status_info]);
1430 }
1431
1432 /**
1433  * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1434  * The author's most recent status will be returned inline.
1435  *
1436  * @param string $type Return type (atom, rss, xml, json)
1437  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1438  */
1439 function api_users_show($type)
1440 {
1441         $a = get_app();
1442
1443         $user_info = api_get_user($a);
1444         $lastwall = q(
1445                 "SELECT `item`.*
1446                         FROM `item`
1447                         INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1448                         WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1449                                 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1450                                 AND `type`!='activity'
1451                                 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1452                         ORDER BY `id` DESC
1453                         LIMIT 1",
1454                 intval(api_user()),
1455                 dbesc(ACTIVITY_POST),
1456                 intval($user_info['cid']),
1457                 dbesc($user_info['url']),
1458                 dbesc(normalise_link($user_info['url'])),
1459                 dbesc($user_info['url']),
1460                 dbesc(normalise_link($user_info['url']))
1461         );
1462
1463         if (DBM::is_result($lastwall)) {
1464                 $lastwall = $lastwall[0];
1465
1466                 $in_reply_to = api_in_reply_to($lastwall);
1467
1468                 $converted = api_convert_item($lastwall);
1469
1470                 if ($type == "xml") {
1471                         $geo = "georss:point";
1472                 } else {
1473                         $geo = "geo";
1474                 }
1475
1476                 $user_info['status'] = [
1477                         'text' => $converted["text"],
1478                         'truncated' => false,
1479                         'created_at' => api_date($lastwall['created']),
1480                         'in_reply_to_status_id' => $in_reply_to['status_id'],
1481                         'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1482                         'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1483                         'id' => intval($lastwall['contact-id']),
1484                         'id_str' => (string) $lastwall['contact-id'],
1485                         'in_reply_to_user_id' => $in_reply_to['user_id'],
1486                         'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1487                         'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1488                         $geo => null,
1489                         'favorited' => $lastwall['starred'] ? true : false,
1490                         'statusnet_html' => $converted["html"],
1491                         'statusnet_conversation_id' => $lastwall['parent'],
1492                         'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1493                 ];
1494
1495                 if (count($converted["attachments"]) > 0) {
1496                         $user_info["status"]["attachments"] = $converted["attachments"];
1497                 }
1498
1499                 if (count($converted["entities"]) > 0) {
1500                         $user_info["status"]["entities"] = $converted["entities"];
1501                 }
1502
1503                 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1504                         $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1505                 }
1506
1507                 if (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1508                         $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) . ')');
1509                 }
1510         }
1511
1512         // "uid" and "self" are only needed for some internal stuff, so remove it from here
1513         unset($user_info["uid"]);
1514         unset($user_info["self"]);
1515
1516         return api_format_data("user", $type, ['user' => $user_info]);
1517 }
1518
1519 /// @TODO move to top of file or somewhere better
1520 api_register_func('api/users/show', 'api_users_show');
1521 api_register_func('api/externalprofile/show', 'api_users_show');
1522
1523 /**
1524  * Search a public user account.
1525  *
1526  * @param string $type Return type (atom, rss, xml, json)
1527  *
1528  * @return array|string
1529  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1530  */
1531 function api_users_search($type)
1532 {
1533         $a = get_app();
1534
1535         $userlist = [];
1536
1537         if (x($_GET, 'q')) {
1538                 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1539
1540                 if (!DBM::is_result($r)) {
1541                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1542                 }
1543
1544                 if (DBM::is_result($r)) {
1545                         $k = 0;
1546                         foreach ($r as $user) {
1547                                 $user_info = api_get_user($a, $user["id"]);
1548
1549                                 if ($type == "xml") {
1550                                         $userlist[$k++.":user"] = $user_info;
1551                                 } else {
1552                                         $userlist[] = $user_info;
1553                                 }
1554                         }
1555                         $userlist = ["users" => $userlist];
1556                 } else {
1557                         throw new BadRequestException("User not found.");
1558                 }
1559         } else {
1560                 throw new BadRequestException("User not found.");
1561         }
1562
1563         return api_format_data("users", $type, $userlist);
1564 }
1565
1566 /// @TODO move to top of file or somewhere better
1567 api_register_func('api/users/search', 'api_users_search');
1568
1569 /**
1570  * Return user objects
1571  *
1572  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1573  *
1574  * @param string $type Return format: json or xml
1575  *
1576  * @return array|string
1577  * @throws NotFoundException if the results are empty.
1578  */
1579 function api_users_lookup($type)
1580 {
1581         $users = [];
1582
1583         if (x($_REQUEST['user_id'])) {
1584                 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1585                         if (!empty($id)) {
1586                                 $users[] = api_get_user(get_app(), $id);
1587                         }
1588                 }
1589         }
1590
1591         if (empty($users)) {
1592                 throw new NotFoundException;
1593         }
1594
1595         return api_format_data("users", $type, ['users' => $users]);
1596 }
1597
1598 /// @TODO move to top of file or somewhere better
1599 api_register_func('api/users/lookup', 'api_users_lookup', true);
1600
1601 /**
1602  * Returns statuses that match a specified query.
1603  *
1604  * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1605  *
1606  * @param string $type Return format: json, xml, atom, rss
1607  *
1608  * @return array|string
1609  * @throws BadRequestException if the "q" parameter is missing.
1610  */
1611 function api_search($type)
1612 {
1613         $data = [];
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
1796         if ($exclude_replies && !$conversation_id) {
1797                 if ($max_id > 0) {
1798                         $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1799                 }
1800
1801                 $r = dba::p(
1802                         "SELECT " . item_fieldlists() . "
1803                         FROM `thread`
1804                         STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1805                         " . item_joins() . "
1806                         STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1807                                 AND NOT `user`.`hidewall`
1808                         AND `verb` = ?
1809                         AND NOT `thread`.`private`
1810                         AND `thread`.`wall`
1811                         AND `thread`.`visible`
1812                         AND NOT `thread`.`deleted`
1813                         AND NOT `thread`.`moderated`
1814                         AND `thread`.`iid` > ?
1815                         $sql_extra
1816                         ORDER BY `thread`.`iid` DESC
1817                         LIMIT " . intval($start) . ", " . intval($count),
1818                         ACTIVITY_POST,
1819                         $since_id
1820                 );
1821
1822                 $r = dba::inArray($r);
1823         } else {
1824                 if ($max_id > 0) {
1825                         $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1826                 }
1827                 if ($conversation_id > 0) {
1828                         $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1829                 }
1830
1831                 $r = dba::p(
1832                         "SELECT " . item_fieldlists() . "
1833                         FROM `item`
1834                         " . item_joins() . "
1835                         STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1836                                 AND NOT `user`.`hidewall`
1837                         AND `verb` = ?
1838                         AND NOT `item`.`private`
1839                         AND `item`.`wall`
1840                         AND `item`.`visible`
1841                         AND NOT `item`.`deleted`
1842                         AND NOT `item`.`moderated`
1843                         AND `item`.`id` > ?
1844                         $sql_extra
1845                         ORDER BY `item`.`id` DESC
1846                         LIMIT " . intval($start) . ", " . intval($count),
1847                         ACTIVITY_POST,
1848                         $since_id
1849                 );
1850
1851                 $r = dba::inArray($r);
1852         }
1853
1854         $ret = api_format_items($r, $user_info, false, $type);
1855
1856         $data = ['status' => $ret];
1857         switch ($type) {
1858                 case "atom":
1859                 case "rss":
1860                         $data = api_rss_extra($a, $data, $user_info);
1861                         break;
1862         }
1863
1864         return api_format_data("statuses", $type, $data);
1865 }
1866
1867 /// @TODO move to top of file or somewhere better
1868 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1869
1870 /**
1871  * Returns the most recent statuses posted by users this node knows about.
1872  *
1873  * @brief Returns the list of public federated posts this node knows about
1874  *
1875  * @param string $type Return format: json, xml, atom, rss
1876  * @return array|string
1877  * @throws ForbiddenException
1878  */
1879 function api_statuses_networkpublic_timeline($type)
1880 {
1881         $a = get_app();
1882
1883         if (api_user() === false) {
1884                 throw new ForbiddenException();
1885         }
1886
1887         $user_info = api_get_user($a);
1888
1889         $since_id        = x($_REQUEST, 'since_id')        ? $_REQUEST['since_id']        : 0;
1890         $max_id          = x($_REQUEST, 'max_id')          ? $_REQUEST['max_id']          : 0;
1891
1892         // pagination
1893         $count = x($_REQUEST, 'count') ? $_REQUEST['count']   : 20;
1894         $page  = x($_REQUEST, 'page')  ? $_REQUEST['page']    : 1;
1895         if ($page < 1) {
1896                 $page = 1;
1897         }
1898         $start = ($page - 1) * $count;
1899
1900         $sql_extra = '';
1901         if ($max_id > 0) {
1902                 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1903         }
1904
1905         $r = dba::p(
1906                 "SELECT " . item_fieldlists() . "
1907                 FROM `thread`
1908                 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1909                 " . item_joins() . "
1910                 WHERE `thread`.`uid` = 0
1911                 AND `verb` = ?
1912                 AND NOT `thread`.`private`
1913                 AND `thread`.`visible`
1914                 AND NOT `thread`.`deleted`
1915                 AND NOT `thread`.`moderated`
1916                 AND `thread`.`iid` > ?
1917                 $sql_extra
1918                 ORDER BY `thread`.`iid` DESC
1919                 LIMIT " . intval($start) . ", " . intval($count),
1920                 ACTIVITY_POST,
1921                 $since_id
1922         );
1923
1924         $r = dba::inArray($r);
1925
1926         $ret = api_format_items($r, $user_info, false, $type);
1927
1928         $data = ['status' => $ret];
1929         switch ($type) {
1930                 case "atom":
1931                 case "rss":
1932                         $data = api_rss_extra($a, $data, $user_info);
1933                         break;
1934         }
1935
1936         return api_format_data("statuses", $type, $data);
1937 }
1938
1939 /// @TODO move to top of file or somewhere better
1940 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1941
1942 /**
1943  * Returns a single status.
1944  *
1945  * @param string $type Return type (atom, rss, xml, json)
1946  *
1947  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1948  */
1949 function api_statuses_show($type)
1950 {
1951         $a = get_app();
1952
1953         if (api_user() === false) {
1954                 throw new ForbiddenException();
1955         }
1956
1957         $user_info = api_get_user($a);
1958
1959         // params
1960         $id = intval($a->argv[3]);
1961
1962         if ($id == 0) {
1963                 $id = intval($_REQUEST["id"]);
1964         }
1965
1966         // Hotot workaround
1967         if ($id == 0) {
1968                 $id = intval($a->argv[4]);
1969         }
1970
1971         logger('API: api_statuses_show: ' . $id);
1972
1973         $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1974
1975         $sql_extra = '';
1976         if ($conversation) {
1977                 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1978         } else {
1979                 $sql_extra .= " AND `item`.`id` = %d";
1980         }
1981
1982         $r = q(
1983                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1984                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1985                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1986                 `contact`.`id` AS `cid`
1987                 FROM `item`
1988                 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1989                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1990                 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1991                 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1992                 $sql_extra",
1993                 intval(api_user()),
1994                 dbesc(ACTIVITY_POST),
1995                 intval($id)
1996         );
1997
1998         /// @TODO How about copying this to above methods which don't check $r ?
1999         if (!DBM::is_result($r)) {
2000                 throw new BadRequestException("There is no status with this id.");
2001         }
2002
2003         $ret = api_format_items($r, $user_info, false, $type);
2004
2005         if ($conversation) {
2006                 $data = ['status' => $ret];
2007                 return api_format_data("statuses", $type, $data);
2008         } else {
2009                 $data = ['status' => $ret[0]];
2010                 return api_format_data("status", $type, $data);
2011         }
2012 }
2013
2014 /// @TODO move to top of file or somewhere better
2015 api_register_func('api/statuses/show', 'api_statuses_show', true);
2016
2017 /**
2018  *
2019  * @param string $type Return type (atom, rss, xml, json)
2020  *
2021  * @todo nothing to say?
2022  */
2023 function api_conversation_show($type)
2024 {
2025         $a = get_app();
2026
2027         if (api_user() === false) {
2028                 throw new ForbiddenException();
2029         }
2030
2031         $user_info = api_get_user($a);
2032
2033         // params
2034         $id = intval($a->argv[3]);
2035         $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2036         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
2037         if ($page < 0) {
2038                 $page = 0;
2039         }
2040         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2041         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2042
2043         $start = $page*$count;
2044
2045         if ($id == 0) {
2046                 $id = intval($_REQUEST["id"]);
2047         }
2048
2049         // Hotot workaround
2050         if ($id == 0) {
2051                 $id = intval($a->argv[4]);
2052         }
2053
2054         logger('API: api_conversation_show: '.$id);
2055
2056         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
2057         if (DBM::is_result($r)) {
2058                 $id = $r[0]["parent"];
2059         }
2060
2061         $sql_extra = '';
2062
2063         if ($max_id > 0) {
2064                 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2065         }
2066
2067         // Not sure why this query was so complicated. We should keep it here for a while,
2068         // just to make sure that we really don't need it.
2069         //      FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2070         //      ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2071
2072         $r = q(
2073                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2074                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2075                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2076                 `contact`.`id` AS `cid`
2077                 FROM `item`
2078                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2079                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2080                 WHERE `item`.`parent` = %d AND `item`.`visible`
2081                 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2082                 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2083                 AND `item`.`id`>%d $sql_extra
2084                 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2085                 intval($id),
2086                 intval(api_user()),
2087                 dbesc(ACTIVITY_POST),
2088                 intval($since_id),
2089                 intval($start),
2090                 intval($count)
2091         );
2092
2093         if (!DBM::is_result($r)) {
2094                 throw new BadRequestException("There is no status with this id.");
2095         }
2096
2097         $ret = api_format_items($r, $user_info, false, $type);
2098
2099         $data = ['status' => $ret];
2100         return api_format_data("statuses", $type, $data);
2101 }
2102
2103 /// @TODO move to top of file or somewhere better
2104 api_register_func('api/conversation/show', 'api_conversation_show', true);
2105 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2106
2107 /**
2108  * Repeats a status.
2109  *
2110  * @param string $type Return type (atom, rss, xml, json)
2111  *
2112  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2113  */
2114 function api_statuses_repeat($type)
2115 {
2116         global $called_api;
2117
2118         $a = get_app();
2119
2120         if (api_user() === false) {
2121                 throw new ForbiddenException();
2122         }
2123
2124         api_get_user($a);
2125
2126         // params
2127         $id = intval($a->argv[3]);
2128
2129         if ($id == 0) {
2130                 $id = intval($_REQUEST["id"]);
2131         }
2132
2133         // Hotot workaround
2134         if ($id == 0) {
2135                 $id = intval($a->argv[4]);
2136         }
2137
2138         logger('API: api_statuses_repeat: '.$id);
2139
2140         $r = q(
2141                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2142                 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2143                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2144                 `contact`.`id` AS `cid`
2145                 FROM `item`
2146                 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2147                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2148                 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2149                 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2150                 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2151                 $sql_extra
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::delete($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         if ($max_id > 0) {
2272                 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2273         }
2274
2275         $r = q(
2276                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2277                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2278                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2279                 `contact`.`id` AS `cid`
2280                 FROM `item` FORCE INDEX (`uid_id`)
2281                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2282                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2283                 WHERE `item`.`uid` = %d AND `verb` = '%s'
2284                 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2285                 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2286                 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2287                 $sql_extra
2288                 AND `item`.`id`>%d
2289                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2290                 intval(api_user()),
2291                 dbesc(ACTIVITY_POST),
2292                 dbesc(protect_sprintf($myurl)),
2293                 dbesc(protect_sprintf($myurl)),
2294                 intval(api_user()),
2295                 intval($since_id),
2296                 intval($start),
2297                 intval($count)
2298         );
2299
2300         $ret = api_format_items($r, $user_info, false, $type);
2301
2302         $data = ['status' => $ret];
2303         switch ($type) {
2304                 case "atom":
2305                 case "rss":
2306                         $data = api_rss_extra($a, $data, $user_info);
2307                         break;
2308         }
2309
2310         return api_format_data("statuses", $type, $data);
2311 }
2312
2313 /// @TODO move to top of file or somewhere better
2314 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2315 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2316
2317 /**
2318  * Returns the most recent statuses posted by the user.
2319  *
2320  * @brief Returns a user's public timeline
2321  *
2322  * @param string $type Either "json" or "xml"
2323  * @return string|array
2324  * @throws ForbiddenException
2325  * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2326  */
2327 function api_statuses_user_timeline($type)
2328 {
2329         $a = get_app();
2330
2331         if (api_user() === false) {
2332                 throw new ForbiddenException();
2333         }
2334
2335         $user_info = api_get_user($a);
2336
2337         logger(
2338                 "api_statuses_user_timeline: api_user: ". api_user() .
2339                         "\nuser_info: ".print_r($user_info, true) .
2340                         "\n_REQUEST:  ".print_r($_REQUEST, true),
2341                 LOGGER_DEBUG
2342         );
2343
2344         $since_id        = x($_REQUEST, 'since_id')        ? $_REQUEST['since_id']        : 0;
2345         $max_id          = x($_REQUEST, 'max_id')          ? $_REQUEST['max_id']          : 0;
2346         $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1                            : 0;
2347         $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2348
2349         // pagination
2350         $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2351         $page  = x($_REQUEST, 'page')  ? $_REQUEST['page']  : 1;
2352         if ($page < 1) {
2353                 $page = 1;
2354         }
2355         $start = ($page - 1) * $count;
2356
2357         $sql_extra = '';
2358         if ($user_info['self'] == 1) {
2359                 $sql_extra .= " AND `item`.`wall` = 1 ";
2360         }
2361
2362         if ($exclude_replies > 0) {
2363                 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2364         }
2365
2366         if ($conversation_id > 0) {
2367                 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2368         }
2369
2370         if ($max_id > 0) {
2371                 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2372         }
2373
2374         $r = q(
2375                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2376                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2377                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2378                 `contact`.`id` AS `cid`
2379                 FROM `item` FORCE INDEX (`uid_contactid_id`)
2380                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2381                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2382                 WHERE `item`.`uid` = %d AND `verb` = '%s'
2383                 AND `item`.`contact-id` = %d
2384                 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2385                 $sql_extra
2386                 AND `item`.`id` > %d
2387                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2388                 intval(api_user()),
2389                 dbesc(ACTIVITY_POST),
2390                 intval($user_info['cid']),
2391                 intval($since_id),
2392                 intval($start),
2393                 intval($count)
2394         );
2395
2396         $ret = api_format_items($r, $user_info, true, $type);
2397
2398         $data = ['status' => $ret];
2399         switch ($type) {
2400                 case "atom":
2401                 case "rss":
2402                         $data = api_rss_extra($a, $data, $user_info);
2403                         break;
2404         }
2405
2406         return api_format_data("statuses", $type, $data);
2407 }
2408
2409 /// @TODO move to top of file or somewhere better
2410 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2411
2412 /**
2413  * Star/unstar an item.
2414  * param: id : id of the item
2415  *
2416  * @param string $type Return type (atom, rss, xml, json)
2417  *
2418  * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2419  */
2420 function api_favorites_create_destroy($type)
2421 {
2422         $a = get_app();
2423
2424         if (api_user() === false) {
2425                 throw new ForbiddenException();
2426         }
2427
2428         // for versioned api.
2429         /// @TODO We need a better global soluton
2430         $action_argv_id = 2;
2431         if ($a->argv[1] == "1.1") {
2432                 $action_argv_id = 3;
2433         }
2434
2435         if ($a->argc <= $action_argv_id) {
2436                 throw new BadRequestException("Invalid request.");
2437         }
2438         $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2439         if ($a->argc == $action_argv_id + 2) {
2440                 $itemid = intval($a->argv[$action_argv_id + 1]);
2441         } else {
2442                 ///  @TODO use x() to check if _REQUEST contains 'id'
2443                 $itemid = intval($_REQUEST['id']);
2444         }
2445
2446         $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2447
2448         if (!DBM::is_result($item) || count($item) == 0) {
2449                 throw new BadRequestException("Invalid item.");
2450         }
2451
2452         switch ($action) {
2453                 case "create":
2454                         $item[0]['starred'] = 1;
2455                         break;
2456                 case "destroy":
2457                         $item[0]['starred'] = 0;
2458                         break;
2459                 default:
2460                         throw new BadRequestException("Invalid action ".$action);
2461         }
2462
2463         $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2464
2465         q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
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 = trim(bbcode($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 = bb_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' => $text,
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         api_get_user($a);
3541
3542         $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3543
3544         $r = q(
3545                 "SELECT `pcontact`.`id` FROM `contact`
3546                         INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3547                         WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3548                 intval(api_user())
3549         );
3550         if (!DBM::is_result($r)) {
3551                 return;
3552         }
3553
3554         $ids = [];
3555         foreach ($r as $rr) {
3556                 if ($stringify_ids) {
3557                         $ids[] = $rr['id'];
3558                 } else {
3559                         $ids[] = intval($rr['id']);
3560                 }
3561         }
3562
3563         return api_format_data("ids", $type, ['id' => $ids]);
3564 }
3565
3566 /**
3567  * Returns the ID of every user the user is following.
3568  *
3569  * @param string $type Return type (atom, rss, xml, json)
3570  *
3571  * @return array|string
3572  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3573  */
3574 function api_friends_ids($type)
3575 {
3576         return api_ff_ids($type);
3577 }
3578
3579 /**
3580  * Returns the ID of every user following the user.
3581  *
3582  * @param string $type Return type (atom, rss, xml, json)
3583  *
3584  * @return array|string
3585  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3586  */
3587 function api_followers_ids($type)
3588 {
3589         return api_ff_ids($type);
3590 }
3591
3592 /// @TODO move to top of file or somewhere better
3593 api_register_func('api/friends/ids', 'api_friends_ids', true);
3594 api_register_func('api/followers/ids', 'api_followers_ids', true);
3595
3596 /**
3597  * Sends a new direct message.
3598  *
3599  * @param string $type Return type (atom, rss, xml, json)
3600  *
3601  * @return array|string
3602  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3603  */
3604 function api_direct_messages_new($type)
3605 {
3606
3607         $a = get_app();
3608
3609         if (api_user() === false) {
3610                 throw new ForbiddenException();
3611         }
3612
3613         if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3614                 return;
3615         }
3616
3617         $sender = api_get_user($a);
3618
3619         if ($_POST['screen_name']) {
3620                 $r = q(
3621                         "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3622                         intval(api_user()),
3623                         dbesc($_POST['screen_name'])
3624                 );
3625
3626                 // Selecting the id by priority, friendica first
3627                 api_best_nickname($r);
3628
3629                 $recipient = api_get_user($a, $r[0]['nurl']);
3630         } else {
3631                 $recipient = api_get_user($a, $_POST['user_id']);
3632         }
3633
3634         $replyto = '';
3635         $sub     = '';
3636         if (x($_REQUEST, 'replyto')) {
3637                 $r = q(
3638                         'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3639                         intval(api_user()),
3640                         intval($_REQUEST['replyto'])
3641                 );
3642                 $replyto = $r[0]['parent-uri'];
3643                 $sub     = $r[0]['title'];
3644         } else {
3645                 if (x($_REQUEST, 'title')) {
3646                         $sub = $_REQUEST['title'];
3647                 } else {
3648                         $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3649                 }
3650         }
3651
3652         $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3653
3654         if ($id > -1) {
3655                 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3656                 $ret = api_format_messages($r[0], $recipient, $sender);
3657         } else {
3658                 $ret = ["error"=>$id];
3659         }
3660
3661         $data = ['direct_message'=>$ret];
3662
3663         switch ($type) {
3664                 case "atom":
3665                 case "rss":
3666                         $data = api_rss_extra($a, $data, $user_info);
3667         }
3668
3669         return api_format_data("direct-messages", $type, $data);
3670 }
3671
3672 /// @TODO move to top of file or somewhere better
3673 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3674
3675 /**
3676  * Destroys a direct message.
3677  *
3678  * @brief delete a direct_message from mail table through api
3679  *
3680  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3681  * @return string
3682  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3683  */
3684 function api_direct_messages_destroy($type)
3685 {
3686         $a = get_app();
3687
3688         if (api_user() === false) {
3689                 throw new ForbiddenException();
3690         }
3691
3692         // params
3693         $user_info = api_get_user($a);
3694         //required
3695         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3696         // optional
3697         $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3698         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3699         /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3700
3701         $uid = $user_info['uid'];
3702         // error if no id or parenturi specified (for clients posting parent-uri as well)
3703         if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3704                 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3705                 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3706         }
3707
3708         // BadRequestException if no id specified (for clients using Twitter API)
3709         if ($id == 0) {
3710                 throw new BadRequestException('Message id not specified');
3711         }
3712
3713         // add parent-uri to sql command if specified by calling app
3714         $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3715
3716         // get data of the specified message id
3717         $r = q(
3718                 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3719                 intval($uid),
3720                 intval($id)
3721         );
3722
3723         // error message if specified id is not in database
3724         if (!DBM::is_result($r)) {
3725                 if ($verbose == "true") {
3726                         $answer = ['result' => 'error', 'message' => 'message id not in database'];
3727                         return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3728                 }
3729                 /// @todo BadRequestException ok for Twitter API clients?
3730                 throw new BadRequestException('message id not in database');
3731         }
3732
3733         // delete message
3734         $result = q(
3735                 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3736                 intval($uid),
3737                 intval($id)
3738         );
3739
3740         if ($verbose == "true") {
3741                 if ($result) {
3742                         // return success
3743                         $answer = ['result' => 'ok', 'message' => 'message deleted'];
3744                         return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3745                 } else {
3746                         $answer = ['result' => 'error', 'message' => 'unknown error'];
3747                         return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3748                 }
3749         }
3750         /// @todo return JSON data like Twitter API not yet implemented
3751 }
3752
3753 /// @TODO move to top of file or somewhere better
3754 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3755
3756 /**
3757  *
3758  * @param string $type Return type (atom, rss, xml, json)
3759  * @param string $box
3760  * @param string $verbose
3761  *
3762  * @return array|string
3763  */
3764 function api_direct_messages_box($type, $box, $verbose)
3765 {
3766         $a = get_app();
3767
3768         if (api_user() === false) {
3769                 throw new ForbiddenException();
3770         }
3771
3772         // params
3773         $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3774         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3775         if ($page < 0) {
3776                 $page = 0;
3777         }
3778
3779         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3780         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3781
3782         $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3783         $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3784
3785         //  caller user info
3786         unset($_REQUEST["user_id"]);
3787         unset($_GET["user_id"]);
3788
3789         unset($_REQUEST["screen_name"]);
3790         unset($_GET["screen_name"]);
3791
3792         $user_info = api_get_user($a);
3793         $profile_url = $user_info["url"];
3794
3795         // pagination
3796         $start = $page * $count;
3797
3798         // filters
3799         if ($box=="sentbox") {
3800                 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3801         } elseif ($box == "conversation") {
3802                 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"])  . "'";
3803         } elseif ($box == "all") {
3804                 $sql_extra = "true";
3805         } elseif ($box == "inbox") {
3806                 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3807         }
3808
3809         if ($max_id > 0) {
3810                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3811         }
3812
3813         if ($user_id != "") {
3814                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3815         } elseif ($screen_name !="") {
3816                 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3817         }
3818
3819         $r = q(
3820                 "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",
3821                 intval(api_user()),
3822                 intval($since_id),
3823                 intval($start),
3824                 intval($count)
3825         );
3826         if ($verbose == "true" && !DBM::is_result($r)) {
3827                 $answer = ['result' => 'error', 'message' => 'no mails available'];
3828                 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3829         }
3830
3831         $ret = [];
3832         foreach ($r as $item) {
3833                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3834                         $recipient = $user_info;
3835                         $sender = api_get_user($a, normalise_link($item['contact-url']));
3836                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3837                         $recipient = api_get_user($a, normalise_link($item['contact-url']));
3838                         $sender = $user_info;
3839                 }
3840
3841                 $ret[] = api_format_messages($item, $recipient, $sender);
3842         }
3843
3844
3845         $data = ['direct_message' => $ret];
3846         switch ($type) {
3847                 case "atom":
3848                 case "rss":
3849                         $data = api_rss_extra($a, $data, $user_info);
3850         }
3851
3852         return api_format_data("direct-messages", $type, $data);
3853 }
3854
3855 /**
3856  * Returns the most recent direct messages sent by the user.
3857  *
3858  * @param string $type Return type (atom, rss, xml, json)
3859  *
3860  * @return array|string
3861  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3862  */
3863 function api_direct_messages_sentbox($type)
3864 {
3865         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3866         return api_direct_messages_box($type, "sentbox", $verbose);
3867 }
3868
3869 /**
3870  * Returns the most recent direct messages sent to the user.
3871  *
3872  * @param string $type Return type (atom, rss, xml, json)
3873  *
3874  * @return array|string
3875  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3876  */
3877 function api_direct_messages_inbox($type)
3878 {
3879         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3880         return api_direct_messages_box($type, "inbox", $verbose);
3881 }
3882
3883 /**
3884  *
3885  * @param string $type Return type (atom, rss, xml, json)
3886  *
3887  * @return array|string
3888  */
3889 function api_direct_messages_all($type)
3890 {
3891         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3892         return api_direct_messages_box($type, "all", $verbose);
3893 }
3894
3895 /**
3896  *
3897  * @param string $type Return type (atom, rss, xml, json)
3898  *
3899  * @return array|string
3900  */
3901 function api_direct_messages_conversation($type)
3902 {
3903         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3904         return api_direct_messages_box($type, "conversation", $verbose);
3905 }
3906
3907 /// @TODO move to top of file or somewhere better
3908 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3909 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3910 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3911 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3912
3913 /**
3914  * Returns an OAuth Request Token.
3915  *
3916  * @see https://oauth.net/core/1.0/#auth_step1
3917  */
3918 function api_oauth_request_token()
3919 {
3920         $oauth1 = new FKOAuth1();
3921         try {
3922                 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3923         } catch (Exception $e) {
3924                 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3925                 killme();
3926         }
3927         echo $r;
3928         killme();
3929 }
3930
3931 /**
3932  * Returns an OAuth Access Token.
3933  *
3934  * @return array|string
3935  * @see https://oauth.net/core/1.0/#auth_step3
3936  */
3937 function api_oauth_access_token()
3938 {
3939         $oauth1 = new FKOAuth1();
3940         try {
3941                 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3942         } catch (Exception $e) {
3943                 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3944                 killme();
3945         }
3946         echo $r;
3947         killme();
3948 }
3949
3950 /// @TODO move to top of file or somewhere better
3951 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3952 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3953
3954
3955 /**
3956  * @brief delete a complete photoalbum with all containing photos from database through api
3957  *
3958  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3959  * @return string
3960  */
3961 function api_fr_photoalbum_delete($type)
3962 {
3963         if (api_user() === false) {
3964                 throw new ForbiddenException();
3965         }
3966         // input params
3967         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3968
3969         // we do not allow calls without album string
3970         if ($album == "") {
3971                 throw new BadRequestException("no albumname specified");
3972         }
3973         // check if album is existing
3974         $r = q(
3975                 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3976                 intval(api_user()),
3977                 dbesc($album)
3978         );
3979         if (!DBM::is_result($r)) {
3980                 throw new BadRequestException("album not available");
3981         }
3982
3983         // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3984         // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3985         foreach ($r as $rr) {
3986                 $photo_item = q(
3987                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3988                         intval(local_user()),
3989                         dbesc($rr['resource-id'])
3990                 );
3991
3992                 if (!DBM::is_result($photo_item)) {
3993                         throw new InternalServerErrorException("problem with deleting items occured");
3994                 }
3995                 Item::delete($photo_item[0]['id']);
3996         }
3997
3998         // now let's delete all photos from the album
3999         $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
4000
4001         // return success of deletion or error message
4002         if ($result) {
4003                 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4004                 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4005         } else {
4006                 throw new InternalServerErrorException("unknown error - deleting from database failed");
4007         }
4008 }
4009
4010 /**
4011  * @brief update the name of the album for all photos of an album
4012  *
4013  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4014  * @return string
4015  */
4016 function api_fr_photoalbum_update($type)
4017 {
4018         if (api_user() === false) {
4019                 throw new ForbiddenException();
4020         }
4021         // input params
4022         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4023         $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4024
4025         // we do not allow calls without album string
4026         if ($album == "") {
4027                 throw new BadRequestException("no albumname specified");
4028         }
4029         if ($album_new == "") {
4030                 throw new BadRequestException("no new albumname specified");
4031         }
4032         // check if album is existing
4033         $r = q(
4034                 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4035                 intval(api_user()),
4036                 dbesc($album)
4037         );
4038         if (!DBM::is_result($r)) {
4039                 throw new BadRequestException("album not available");
4040         }
4041         // now let's update all photos to the albumname
4042         $result = q(
4043                 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
4044                 dbesc($album_new),
4045                 intval(api_user()),
4046                 dbesc($album)
4047         );
4048
4049         // return success of updating or error message
4050         if ($result) {
4051                 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4052                 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4053         } else {
4054                 throw new InternalServerErrorException("unknown error - updating in database failed");
4055         }
4056 }
4057
4058
4059 /**
4060  * @brief list all photos of the authenticated user
4061  *
4062  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4063  * @return string
4064  */
4065 function api_fr_photos_list($type)
4066 {
4067         if (api_user() === false) {
4068                 throw new ForbiddenException();
4069         }
4070         $r = q(
4071                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4072                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4073                 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4074                 intval(local_user())
4075         );
4076         $typetoext = [
4077                 'image/jpeg' => 'jpg',
4078                 'image/png' => 'png',
4079                 'image/gif' => 'gif'
4080         ];
4081         $data = ['photo'=>[]];
4082         if (DBM::is_result($r)) {
4083                 foreach ($r as $rr) {
4084                         $photo = [];
4085                         $photo['id'] = $rr['resource-id'];
4086                         $photo['album'] = $rr['album'];
4087                         $photo['filename'] = $rr['filename'];
4088                         $photo['type'] = $rr['type'];
4089                         $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4090                         $photo['created'] = $rr['created'];
4091                         $photo['edited'] = $rr['edited'];
4092                         $photo['desc'] = $rr['desc'];
4093
4094                         if ($type == "xml") {
4095                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4096                         } else {
4097                                 $photo['thumb'] = $thumb;
4098                                 $data['photo'][] = $photo;
4099                         }
4100                 }
4101         }
4102         return api_format_data("photos", $type, $data);
4103 }
4104
4105 /**
4106  * @brief upload a new photo or change an existing photo
4107  *
4108  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4109  * @return string
4110  */
4111 function api_fr_photo_create_update($type)
4112 {
4113         if (api_user() === false) {
4114                 throw new ForbiddenException();
4115         }
4116         // input params
4117         $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4118         $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4119         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4120         $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4121         $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4122         $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4123         $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4124         $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4125         $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4126
4127         // do several checks on input parameters
4128         // we do not allow calls without album string
4129         if ($album == null) {
4130                 throw new BadRequestException("no albumname specified");
4131         }
4132         // if photo_id == null --> we are uploading a new photo
4133         if ($photo_id == null) {
4134                 $mode = "create";
4135
4136                 // error if no media posted in create-mode
4137                 if (!x($_FILES, 'media')) {
4138                         // Output error
4139                         throw new BadRequestException("no media data submitted");
4140                 }
4141
4142                 // album_new will be ignored in create-mode
4143                 $album_new = "";
4144         } else {
4145                 $mode = "update";
4146
4147                 // check if photo is existing in database
4148                 $r = q(
4149                         "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4150                         intval(api_user()),
4151                         dbesc($photo_id),
4152                         dbesc($album)
4153                 );
4154                 if (!DBM::is_result($r)) {
4155                         throw new BadRequestException("photo not available");
4156                 }
4157         }
4158
4159         // checks on acl strings provided by clients
4160         $acl_input_error = false;
4161         $acl_input_error |= check_acl_input($allow_cid);
4162         $acl_input_error |= check_acl_input($deny_cid);
4163         $acl_input_error |= check_acl_input($allow_gid);
4164         $acl_input_error |= check_acl_input($deny_gid);
4165         if ($acl_input_error) {
4166                 throw new BadRequestException("acl data invalid");
4167         }
4168         // now let's upload the new media in create-mode
4169         if ($mode == "create") {
4170                 $media = $_FILES['media'];
4171                 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4172
4173                 // return success of updating or error message
4174                 if (!is_null($data)) {
4175                         return api_format_data("photo_create", $type, $data);
4176                 } else {
4177                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4178                 }
4179         }
4180
4181         // now let's do the changes in update-mode
4182         if ($mode == "update") {
4183                 $sql_extra = "";
4184
4185                 if (!is_null($desc)) {
4186                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4187                 }
4188
4189                 if (!is_null($album_new)) {
4190                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4191                 }
4192
4193                 if (!is_null($allow_cid)) {
4194                         $allow_cid = trim($allow_cid);
4195                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4196                 }
4197
4198                 if (!is_null($deny_cid)) {
4199                         $deny_cid = trim($deny_cid);
4200                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4201                 }
4202
4203                 if (!is_null($allow_gid)) {
4204                         $allow_gid = trim($allow_gid);
4205                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4206                 }
4207
4208                 if (!is_null($deny_gid)) {
4209                         $deny_gid = trim($deny_gid);
4210                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4211                 }
4212
4213                 $result = false;
4214                 if ($sql_extra != "") {
4215                         $nothingtodo = false;
4216                         $result = q(
4217                                 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4218                                 $sql_extra,
4219                                 DateTimeFormat::utcNow(),   // update edited timestamp
4220                                 intval(api_user()),
4221                                 dbesc($photo_id),
4222                                 dbesc($album)
4223                         );
4224                 } else {
4225                         $nothingtodo = true;
4226                 }
4227
4228                 if (x($_FILES, 'media')) {
4229                         $nothingtodo = false;
4230                         $media = $_FILES['media'];
4231                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4232                         if (!is_null($data)) {
4233                                 return api_format_data("photo_update", $type, $data);
4234                         }
4235                 }
4236
4237                 // return success of updating or error message
4238                 if ($result) {
4239                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4240                         return api_format_data("photo_update", $type, ['$result' => $answer]);
4241                 } else {
4242                         if ($nothingtodo) {
4243                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4244                                 return api_format_data("photo_update", $type, ['$result' => $answer]);
4245                         }
4246                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4247                 }
4248         }
4249         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4250 }
4251
4252
4253 /**
4254  * @brief delete a single photo from the database through api
4255  *
4256  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4257  * @return string
4258  */
4259 function api_fr_photo_delete($type)
4260 {
4261         if (api_user() === false) {
4262                 throw new ForbiddenException();
4263         }
4264         // input params
4265         $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4266
4267         // do several checks on input parameters
4268         // we do not allow calls without photo id
4269         if ($photo_id == null) {
4270                 throw new BadRequestException("no photo_id specified");
4271         }
4272         // check if photo is existing in database
4273         $r = q(
4274                 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4275                 intval(api_user()),
4276                 dbesc($photo_id)
4277         );
4278         if (!DBM::is_result($r)) {
4279                 throw new BadRequestException("photo not available");
4280         }
4281         // now we can perform on the deletion of the photo
4282         $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4283
4284         // return success of deletion or error message
4285         if ($result) {
4286                 // retrieve the id of the parent element (the photo element)
4287                 $photo_item = q(
4288                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4289                         intval(local_user()),
4290                         dbesc($photo_id)
4291                 );
4292
4293                 if (!DBM::is_result($photo_item)) {
4294                         throw new InternalServerErrorException("problem with deleting items occured");
4295                 }
4296                 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4297                 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4298                 Item::delete($photo_item[0]['id']);
4299
4300                 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4301                 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4302         } else {
4303                 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4304         }
4305 }
4306
4307
4308 /**
4309  * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4310  *
4311  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4312  * @return string|array
4313  */
4314 function api_fr_photo_detail($type)
4315 {
4316         if (api_user() === false) {
4317                 throw new ForbiddenException();
4318         }
4319         if (!x($_REQUEST, 'photo_id')) {
4320                 throw new BadRequestException("No photo id.");
4321         }
4322
4323         $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4324         $photo_id = $_REQUEST['photo_id'];
4325
4326         // prepare json/xml output with data from database for the requested photo
4327         $data = prepare_photo_data($type, $scale, $photo_id);
4328
4329         return api_format_data("photo_detail", $type, $data);
4330 }
4331
4332
4333 /**
4334  * Updates the user’s profile image.
4335  *
4336  * @brief updates the profile image for the user (either a specified profile or the default profile)
4337  *
4338  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4339  *
4340  * @return string
4341  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4342  */
4343 function api_account_update_profile_image($type)
4344 {
4345         if (api_user() === false) {
4346                 throw new ForbiddenException();
4347         }
4348         // input params
4349         $profileid = defaults($_REQUEST, 'profile_id', 0);
4350
4351         // error if image data is missing
4352         if (!x($_FILES, 'image')) {
4353                 throw new BadRequestException("no media data submitted");
4354         }
4355
4356         // check if specified profile id is valid
4357         if ($profileid != 0) {
4358                 $r = q(
4359                         "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4360                         intval(api_user()),
4361                         intval($profileid)
4362                 );
4363                 // error message if specified profile id is not in database
4364                 if (!DBM::is_result($r)) {
4365                         throw new BadRequestException("profile_id not available");
4366                 }
4367                 $is_default_profile = $r['profile'];
4368         } else {
4369                 $is_default_profile = 1;
4370         }
4371
4372         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4373         $media = null;
4374         if (x($_FILES, 'image')) {
4375                 $media = $_FILES['image'];
4376         } elseif (x($_FILES, 'media')) {
4377                 $media = $_FILES['media'];
4378         }
4379         // save new profile image
4380         $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4381
4382         // get filetype
4383         if (is_array($media['type'])) {
4384                 $filetype = $media['type'][0];
4385         } else {
4386                 $filetype = $media['type'];
4387         }
4388         if ($filetype == "image/jpeg") {
4389                 $fileext = "jpg";
4390         } elseif ($filetype == "image/png") {
4391                 $fileext = "png";
4392         }
4393         // change specified profile or all profiles to the new resource-id
4394         if ($is_default_profile) {
4395                 q(
4396                         "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4397                         dbesc($data['photo']['id']),
4398                         intval(local_user())
4399                 );
4400
4401                 q(
4402                         "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s'  WHERE `self` AND `uid` = %d",
4403                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4404                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4405                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4406                         intval(local_user())
4407                 );
4408         } else {
4409                 q(
4410                         "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4411                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4412                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4413                         intval($_REQUEST['profile']),
4414                         intval(local_user())
4415                 );
4416         }
4417
4418         // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4419         // so that browsers will do a cache update unconditionally
4420
4421         q(
4422                 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4423                 dbesc(DateTimeFormat::utcNow()),
4424                 intval(local_user())
4425         );
4426
4427         // Update global directory in background
4428         //$user = api_get_user(get_app());
4429         $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4430         if ($url && strlen(Config::get('system', 'directory'))) {
4431                 Worker::add(PRIORITY_LOW, "Directory", $url);
4432         }
4433
4434         Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4435
4436         // output for client
4437         if ($data) {
4438                 return api_account_verify_credentials($type);
4439         } else {
4440                 // SaveMediaToDatabase failed for some reason
4441                 throw new InternalServerErrorException("image upload failed");
4442         }
4443 }
4444
4445 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4446 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4447 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4448 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4449 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4450 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4451 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4452 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4453 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4454
4455 /**
4456  * Update user profile
4457  *
4458  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4459  *
4460  * @return array|string
4461  */
4462 function api_account_update_profile($type)
4463 {
4464         $local_user = api_user();
4465         $api_user = api_get_user(get_app());
4466
4467         if (!empty($_POST['name'])) {
4468                 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4469                 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4470                 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4471                 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4472         }
4473
4474         if (isset($_POST['description'])) {
4475                 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4476                 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4477                 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4478         }
4479
4480         Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4481         // Update global directory in background
4482         if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4483                 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4484         }
4485
4486         return api_account_verify_credentials($type);
4487 }
4488
4489 /// @TODO move to top of file or somewhere better
4490 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4491
4492 /**
4493  *
4494  * @param string $acl_string
4495  */
4496 function check_acl_input($acl_string)
4497 {
4498         if ($acl_string == null || $acl_string == " ") {
4499                 return false;
4500         }
4501         $contact_not_found = false;
4502
4503         // split <x><y><z> into array of cid's
4504         preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4505
4506         // check for each cid if it is available on server
4507         $cid_array = $array[0];
4508         foreach ($cid_array as $cid) {
4509                 $cid = str_replace("<", "", $cid);
4510                 $cid = str_replace(">", "", $cid);
4511                 $contact = q(
4512                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4513                         intval($cid),
4514                         intval(api_user())
4515                 );
4516                 $contact_not_found |= !DBM::is_result($contact);
4517         }
4518         return $contact_not_found;
4519 }
4520
4521 /**
4522  *
4523  * @param string  $mediatype
4524  * @param array   $media
4525  * @param string  $type
4526  * @param string  $album
4527  * @param string  $allow_cid
4528  * @param string  $deny_cid
4529  * @param string  $allow_gid
4530  * @param string  $deny_gid
4531  * @param string  $desc
4532  * @param integer $profile
4533  * @param boolean $visibility
4534  * @param string  $photo_id
4535  */
4536 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)
4537 {
4538         $visitor   = 0;
4539         $src = "";
4540         $filetype = "";
4541         $filename = "";
4542         $filesize = 0;
4543
4544         if (is_array($media)) {
4545                 if (is_array($media['tmp_name'])) {
4546                         $src = $media['tmp_name'][0];
4547                 } else {
4548                         $src = $media['tmp_name'];
4549                 }
4550                 if (is_array($media['name'])) {
4551                         $filename = basename($media['name'][0]);
4552                 } else {
4553                         $filename = basename($media['name']);
4554                 }
4555                 if (is_array($media['size'])) {
4556                         $filesize = intval($media['size'][0]);
4557                 } else {
4558                         $filesize = intval($media['size']);
4559                 }
4560                 if (is_array($media['type'])) {
4561                         $filetype = $media['type'][0];
4562                 } else {
4563                         $filetype = $media['type'];
4564                 }
4565         }
4566
4567         if ($filetype == "") {
4568                 $filetype=Image::guessType($filename);
4569         }
4570         $imagedata = getimagesize($src);
4571         if ($imagedata) {
4572                 $filetype = $imagedata['mime'];
4573         }
4574         logger(
4575                 "File upload src: " . $src . " - filename: " . $filename .
4576                 " - size: " . $filesize . " - type: " . $filetype,
4577                 LOGGER_DEBUG
4578         );
4579
4580         // check if there was a php upload error
4581         if ($filesize == 0 && $media['error'] == 1) {
4582                 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4583         }
4584         // check against max upload size within Friendica instance
4585         $maximagesize = Config::get('system', 'maximagesize');
4586         if ($maximagesize && ($filesize > $maximagesize)) {
4587                 $formattedBytes = formatBytes($maximagesize);
4588                 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4589         }
4590
4591         // create Photo instance with the data of the image
4592         $imagedata = @file_get_contents($src);
4593         $Image = new Image($imagedata, $filetype);
4594         if (! $Image->isValid()) {
4595                 throw new InternalServerErrorException("unable to process image data");
4596         }
4597
4598         // check orientation of image
4599         $Image->orient($src);
4600         @unlink($src);
4601
4602         // check max length of images on server
4603         $max_length = Config::get('system', 'max_image_length');
4604         if (! $max_length) {
4605                 $max_length = MAX_IMAGE_LENGTH;
4606         }
4607         if ($max_length > 0) {
4608                 $Image->scaleDown($max_length);
4609                 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4610         }
4611         $width = $Image->getWidth();
4612         $height = $Image->getHeight();
4613
4614         // create a new resource-id if not already provided
4615         $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4616
4617         if ($mediatype == "photo") {
4618                 // upload normal image (scales 0, 1, 2)
4619                 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4620
4621                 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4622                 if (! $r) {
4623                         logger("photo upload: image upload with scale 0 (original size) failed");
4624                 }
4625                 if ($width > 640 || $height > 640) {
4626                         $Image->scaleDown(640);
4627                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4628                         if (! $r) {
4629                                 logger("photo upload: image upload with scale 1 (640x640) failed");
4630                         }
4631                 }
4632
4633                 if ($width > 320 || $height > 320) {
4634                         $Image->scaleDown(320);
4635                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4636                         if (! $r) {
4637                                 logger("photo upload: image upload with scale 2 (320x320) failed");
4638                         }
4639                 }
4640                 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4641         } elseif ($mediatype == "profileimage") {
4642                 // upload profile image (scales 4, 5, 6)
4643                 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4644
4645                 if ($width > 175 || $height > 175) {
4646                         $Image->scaleDown(175);
4647                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4648                         if (! $r) {
4649                                 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4650                         }
4651                 }
4652
4653                 if ($width > 80 || $height > 80) {
4654                         $Image->scaleDown(80);
4655                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4656                         if (! $r) {
4657                                 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4658                         }
4659                 }
4660
4661                 if ($width > 48 || $height > 48) {
4662                         $Image->scaleDown(48);
4663                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4664                         if (! $r) {
4665                                 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4666                         }
4667                 }
4668                 $Image->__destruct();
4669                 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4670         }
4671
4672         if ($r) {
4673                 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4674                 if ($photo_id == null && $mediatype == "photo") {
4675                         post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4676                 }
4677                 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4678                 return prepare_photo_data($type, false, $hash);
4679         } else {
4680                 throw new InternalServerErrorException("image upload failed");
4681         }
4682 }
4683
4684 /**
4685  *
4686  * @param string  $hash
4687  * @param string  $allow_cid
4688  * @param string  $deny_cid
4689  * @param string  $allow_gid
4690  * @param string  $deny_gid
4691  * @param string  $filetype
4692  * @param boolean $visibility
4693  */
4694 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4695 {
4696         // get data about the api authenticated user
4697         $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4698         $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4699
4700         $arr = [];
4701         $arr['guid']          = get_guid(32);
4702         $arr['uid']           = intval(api_user());
4703         $arr['uri']           = $uri;
4704         $arr['parent-uri']    = $uri;
4705         $arr['type']          = 'photo';
4706         $arr['wall']          = 1;
4707         $arr['resource-id']   = $hash;
4708         $arr['contact-id']    = $owner_record[0]['id'];
4709         $arr['owner-name']    = $owner_record[0]['name'];
4710         $arr['owner-link']    = $owner_record[0]['url'];
4711         $arr['owner-avatar']  = $owner_record[0]['thumb'];
4712         $arr['author-name']   = $owner_record[0]['name'];
4713         $arr['author-link']   = $owner_record[0]['url'];
4714         $arr['author-avatar'] = $owner_record[0]['thumb'];
4715         $arr['title']         = "";
4716         $arr['allow_cid']     = $allow_cid;
4717         $arr['allow_gid']     = $allow_gid;
4718         $arr['deny_cid']      = $deny_cid;
4719         $arr['deny_gid']      = $deny_gid;
4720         $arr['visible']       = $visibility;
4721         $arr['origin']        = 1;
4722
4723         $typetoext = [
4724                         'image/jpeg' => 'jpg',
4725                         'image/png' => 'png',
4726                         'image/gif' => 'gif'
4727                         ];
4728
4729         // adds link to the thumbnail scale photo
4730         $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4731                                 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4732                                 . '[/url]';
4733
4734         // do the magic for storing the item in the database and trigger the federation to other contacts
4735         Item::insert($arr);
4736 }
4737
4738 /**
4739  *
4740  * @param string $type
4741  * @param int    $scale
4742  * @param string $photo_id
4743  *
4744  * @return array
4745  */
4746 function prepare_photo_data($type, $scale, $photo_id)
4747 {
4748         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4749         $data_sql = ($scale === false ? "" : "data, ");
4750
4751         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4752         // clients needs to convert this in their way for further processing
4753         $r = q(
4754                 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4755                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4756                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4757                         FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4758                 $data_sql,
4759                 intval(local_user()),
4760                 dbesc($photo_id),
4761                 $scale_sql
4762         );
4763
4764         $typetoext = [
4765                 'image/jpeg' => 'jpg',
4766                 'image/png' => 'png',
4767                 'image/gif' => 'gif'
4768         ];
4769
4770         // prepare output data for photo
4771         if (DBM::is_result($r)) {
4772                 $data = ['photo' => $r[0]];
4773                 $data['photo']['id'] = $data['photo']['resource-id'];
4774                 if ($scale !== false) {
4775                         $data['photo']['data'] = base64_encode($data['photo']['data']);
4776                 } else {
4777                         unset($data['photo']['datasize']); //needed only with scale param
4778                 }
4779                 if ($type == "xml") {
4780                         $data['photo']['links'] = [];
4781                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4782                                 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4783                                                                                 "scale" => $k,
4784                                                                                 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4785                         }
4786                 } else {
4787                         $data['photo']['link'] = [];
4788                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4789                         $i = 0;
4790                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4791                                 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4792                                 $i++;
4793                         }
4794                 }
4795                 unset($data['photo']['resource-id']);
4796                 unset($data['photo']['minscale']);
4797                 unset($data['photo']['maxscale']);
4798         } else {
4799                 throw new NotFoundException();
4800         }
4801
4802         // retrieve item element for getting activities (like, dislike etc.) related to photo
4803         $item = q(
4804                 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4805                 intval(local_user()),
4806                 dbesc($photo_id)
4807         );
4808         $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4809
4810         // retrieve comments on photo
4811         $r = q(
4812                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4813                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4814                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4815                 `contact`.`id` AS `cid`
4816                 FROM `item`
4817                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4818                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4819                 WHERE `item`.`parent` = %d AND `item`.`visible`
4820                 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4821                 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4822                 intval($item[0]['parent']),
4823                 intval(api_user()),
4824                 dbesc(ACTIVITY_POST)
4825         );
4826
4827         // prepare output of comments
4828         $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4829         $comments = [];
4830         if ($type == "xml") {
4831                 $k = 0;
4832                 foreach ($commentData as $comment) {
4833                         $comments[$k++ . ":comment"] = $comment;
4834                 }
4835         } else {
4836                 foreach ($commentData as $comment) {
4837                         $comments[] = $comment;
4838                 }
4839         }
4840         $data['photo']['friendica_comments'] = $comments;
4841
4842         // include info if rights on photo and rights on item are mismatching
4843         $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4844                 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4845                 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4846                 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4847         $data['photo']['rights_mismatch'] = $rights_mismatch;
4848
4849         return $data;
4850 }
4851
4852
4853 /**
4854  * Similar as /mod/redir.php
4855  * redirect to 'url' after dfrn auth
4856  *
4857  * Why this when there is mod/redir.php already?
4858  * This use api_user() and api_login()
4859  *
4860  * params
4861  *              c_url: url of remote contact to auth to
4862  *              url: string, url to redirect after auth
4863  */
4864 function api_friendica_remoteauth()
4865 {
4866         $url = (x($_GET, 'url') ? $_GET['url'] : '');
4867         $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4868
4869         if ($url === '' || $c_url === '') {
4870                 throw new BadRequestException("Wrong parameters.");
4871         }
4872
4873         $c_url = normalise_link($c_url);
4874
4875         // traditional DFRN
4876
4877         $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4878
4879         if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4880                 throw new BadRequestException("Unknown contact");
4881         }
4882
4883         $cid = $contact['id'];
4884
4885         $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4886
4887         if ($contact['duplex'] && $contact['issued-id']) {
4888                 $orig_id = $contact['issued-id'];
4889                 $dfrn_id = '1:' . $orig_id;
4890         }
4891         if ($contact['duplex'] && $contact['dfrn-id']) {
4892                 $orig_id = $contact['dfrn-id'];
4893                 $dfrn_id = '0:' . $orig_id;
4894         }
4895
4896         $sec = random_string();
4897
4898         q(
4899                 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4900                 VALUES( %d, %s, '%s', '%s', %d )",
4901                 intval(api_user()),
4902                 intval($cid),
4903                 dbesc($dfrn_id),
4904                 dbesc($sec),
4905                 intval(time() + 45)
4906         );
4907
4908         logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4909         $dest = ($url ? '&destination_url=' . $url : '');
4910         goaway(
4911                 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4912                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4913                 . '&type=profile&sec=' . $sec . $dest . $quiet
4914         );
4915 }
4916 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4917
4918 /**
4919  * @brief Return the item shared, if the item contains only the [share] tag
4920  *
4921  * @param array $item Sharer item
4922  * @return array|false Shared item or false if not a reshare
4923  */
4924 function api_share_as_retweet(&$item)
4925 {
4926         $body = trim($item["body"]);
4927
4928         if (Diaspora::isReshare($body, false)===false) {
4929                 return false;
4930         }
4931
4932         /// @TODO "$1" should maybe mean '$1' ?
4933         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4934         /*
4935                 * Skip if there is no shared message in there
4936                 * we already checked this in diaspora::isReshare()
4937                 * but better one more than one less...
4938                 */
4939         if ($body == $attributes) {
4940                 return false;
4941         }
4942
4943
4944         // build the fake reshared item
4945         $reshared_item = $item;
4946
4947         $author = "";
4948         preg_match("/author='(.*?)'/ism", $attributes, $matches);
4949         if ($matches[1] != "") {
4950                 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4951         }
4952
4953         preg_match('/author="(.*?)"/ism', $attributes, $matches);
4954         if ($matches[1] != "") {
4955                 $author = $matches[1];
4956         }
4957
4958         $profile = "";
4959         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4960         if ($matches[1] != "") {
4961                 $profile = $matches[1];
4962         }
4963
4964         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4965         if ($matches[1] != "") {
4966                 $profile = $matches[1];
4967         }
4968
4969         $avatar = "";
4970         preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4971         if ($matches[1] != "") {
4972                 $avatar = $matches[1];
4973         }
4974
4975         preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4976         if ($matches[1] != "") {
4977                 $avatar = $matches[1];
4978         }
4979
4980         $link = "";
4981         preg_match("/link='(.*?)'/ism", $attributes, $matches);
4982         if ($matches[1] != "") {
4983                 $link = $matches[1];
4984         }
4985
4986         preg_match('/link="(.*?)"/ism', $attributes, $matches);
4987         if ($matches[1] != "") {
4988                 $link = $matches[1];
4989         }
4990
4991         $posted = "";
4992         preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4993         if ($matches[1] != "") {
4994                 $posted = $matches[1];
4995         }
4996
4997         preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4998         if ($matches[1] != "") {
4999                 $posted = $matches[1];
5000         }
5001
5002         $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5003
5004         if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5005                 return false;
5006         }
5007
5008         $reshared_item["body"] = $shared_body;
5009         $reshared_item["author-name"] = $author;
5010         $reshared_item["author-link"] = $profile;
5011         $reshared_item["author-avatar"] = $avatar;
5012         $reshared_item["plink"] = $link;
5013         $reshared_item["created"] = $posted;
5014         $reshared_item["edited"] = $posted;
5015
5016         return $reshared_item;
5017 }
5018
5019 /**
5020  *
5021  * @param string $profile
5022  *
5023  * @return string|false
5024  * @todo remove trailing junk from profile url
5025  * @todo pump.io check has to check the website
5026  */
5027 function api_get_nick($profile)
5028 {
5029         $nick = "";
5030
5031         $r = q(
5032                 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5033                 dbesc(normalise_link($profile))
5034         );
5035
5036         if (DBM::is_result($r)) {
5037                 $nick = $r[0]["nick"];
5038         }
5039
5040         if (!$nick == "") {
5041                 $r = q(
5042                         "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5043                         dbesc(normalise_link($profile))
5044                 );
5045
5046                 if (DBM::is_result($r)) {
5047                         $nick = $r[0]["nick"];
5048                 }
5049         }
5050
5051         if (!$nick == "") {
5052                 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5053                 if ($friendica != $profile) {
5054                         $nick = $friendica;
5055                 }
5056         }
5057
5058         if (!$nick == "") {
5059                 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5060                 if ($diaspora != $profile) {
5061                         $nick = $diaspora;
5062                 }
5063         }
5064
5065         if (!$nick == "") {
5066                 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5067                 if ($twitter != $profile) {
5068                         $nick = $twitter;
5069                 }
5070         }
5071
5072
5073         if (!$nick == "") {
5074                 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5075                 if ($StatusnetHost != $profile) {
5076                         $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5077                         if ($StatusnetUser != $profile) {
5078                                 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5079                                 $user = json_decode($UserData);
5080                                 if ($user) {
5081                                         $nick = $user->screen_name;
5082                                 }
5083                         }
5084                 }
5085         }
5086
5087         // To-Do: look at the page if its really a pumpio site
5088         //if (!$nick == "") {
5089         //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5090         //      if ($pumpio != $profile)
5091         //              $nick = $pumpio;
5092                 //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5093
5094         //}
5095
5096         if ($nick != "") {
5097                 return $nick;
5098         }
5099
5100         return false;
5101 }
5102
5103 /**
5104  *
5105  * @param array $item
5106  *
5107  * @return array
5108  */
5109 function api_in_reply_to($item)
5110 {
5111         $in_reply_to = [];
5112
5113         $in_reply_to['status_id'] = null;
5114         $in_reply_to['user_id'] = null;
5115         $in_reply_to['status_id_str'] = null;
5116         $in_reply_to['user_id_str'] = null;
5117         $in_reply_to['screen_name'] = null;
5118
5119         if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5120                 $r = q(
5121                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5122                         intval($item['uid']),
5123                         dbesc($item['thr-parent'])
5124                 );
5125
5126                 if (DBM::is_result($r)) {
5127                         $in_reply_to['status_id'] = intval($r[0]['id']);
5128                 } else {
5129                         $in_reply_to['status_id'] = intval($item['parent']);
5130                 }
5131
5132                 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5133
5134                 $r = q(
5135                         "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
5136                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5137                         WHERE `item`.`id` = %d LIMIT 1",
5138                         intval($in_reply_to['status_id'])
5139                 );
5140
5141                 if (DBM::is_result($r)) {
5142                         if ($r[0]['nick'] == "") {
5143                                 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5144                         }
5145
5146                         $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5147                         $in_reply_to['user_id'] = intval($r[0]['id']);
5148                         $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5149                 }
5150
5151                 // There seems to be situation, where both fields are identical:
5152                 // https://github.com/friendica/friendica/issues/1010
5153                 // This is a bugfix for that.
5154                 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5155                         logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5156                         $in_reply_to['status_id'] = null;
5157                         $in_reply_to['user_id'] = null;
5158                         $in_reply_to['status_id_str'] = null;
5159                         $in_reply_to['user_id_str'] = null;
5160                         $in_reply_to['screen_name'] = null;
5161                 }
5162         }
5163
5164         return $in_reply_to;
5165 }
5166
5167 /**
5168  *
5169  * @param string $Text
5170  *
5171  * @return string
5172  */
5173 function api_clean_plain_items($Text)
5174 {
5175         $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5176
5177         $Text = bb_CleanPictureLinks($Text);
5178         $URLSearchString = "^\[\]";
5179
5180         $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
5181
5182         if ($include_entities == "true") {
5183                 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
5184         }
5185
5186         // Simplify "attachment" element
5187         $Text = api_clean_attachments($Text);
5188
5189         return($Text);
5190 }
5191
5192 /**
5193  * @brief Removes most sharing information for API text export
5194  *
5195  * @param string $body The original body
5196  *
5197  * @return string Cleaned body
5198  */
5199 function api_clean_attachments($body)
5200 {
5201         $data = BBCode::getAttachmentData($body);
5202
5203         if (!$data) {
5204                 return $body;
5205         }
5206         $body = "";
5207
5208         if (isset($data["text"])) {
5209                 $body = $data["text"];
5210         }
5211         if (($body == "") && isset($data["title"])) {
5212                 $body = $data["title"];
5213         }
5214         if (isset($data["url"])) {
5215                 $body .= "\n".$data["url"];
5216         }
5217         $body .= $data["after"];
5218
5219         return $body;
5220 }
5221
5222 /**
5223  *
5224  * @param array $contacts
5225  *
5226  * @return array
5227  */
5228 function api_best_nickname(&$contacts)
5229 {
5230         $best_contact = [];
5231
5232         if (count($contact) == 0) {
5233                 return;
5234         }
5235
5236         foreach ($contacts as $contact) {
5237                 if ($contact["network"] == "") {
5238                         $contact["network"] = "dfrn";
5239                         $best_contact = [$contact];
5240                 }
5241         }
5242
5243         if (sizeof($best_contact) == 0) {
5244                 foreach ($contacts as $contact) {
5245                         if ($contact["network"] == "dfrn") {
5246                                 $best_contact = [$contact];
5247                         }
5248                 }
5249         }
5250
5251         if (sizeof($best_contact) == 0) {
5252                 foreach ($contacts as $contact) {
5253                         if ($contact["network"] == "dspr") {
5254                                 $best_contact = [$contact];
5255                         }
5256                 }
5257         }
5258
5259         if (sizeof($best_contact) == 0) {
5260                 foreach ($contacts as $contact) {
5261                         if ($contact["network"] == "stat") {
5262                                 $best_contact = [$contact];
5263                         }
5264                 }
5265         }
5266
5267         if (sizeof($best_contact) == 0) {
5268                 foreach ($contacts as $contact) {
5269                         if ($contact["network"] == "pump") {
5270                                 $best_contact = [$contact];
5271                         }
5272                 }
5273         }
5274
5275         if (sizeof($best_contact) == 0) {
5276                 foreach ($contacts as $contact) {
5277                         if ($contact["network"] == "twit") {
5278                                 $best_contact = [$contact];
5279                         }
5280                 }
5281         }
5282
5283         if (sizeof($best_contact) == 1) {
5284                 $contacts = $best_contact;
5285         } else {
5286                 $contacts = [$contacts[0]];
5287         }
5288 }
5289
5290 /**
5291  * Return all or a specified group of the user with the containing contacts.
5292  *
5293  * @param string $type Return type (atom, rss, xml, json)
5294  *
5295  * @return array|string
5296  */
5297 function api_friendica_group_show($type)
5298 {
5299         $a = get_app();
5300
5301         if (api_user() === false) {
5302                 throw new ForbiddenException();
5303         }
5304
5305         // params
5306         $user_info = api_get_user($a);
5307         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5308         $uid = $user_info['uid'];
5309
5310         // get data of the specified group id or all groups if not specified
5311         if ($gid != 0) {
5312                 $r = q(
5313                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5314                         intval($uid),
5315                         intval($gid)
5316                 );
5317                 // error message if specified gid is not in database
5318                 if (!DBM::is_result($r)) {
5319                         throw new BadRequestException("gid not available");
5320                 }
5321         } else {
5322                 $r = q(
5323                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5324                         intval($uid)
5325                 );
5326         }
5327
5328         // loop through all groups and retrieve all members for adding data in the user array
5329         foreach ($r as $rr) {
5330                 $members = Contact::getByGroupId($rr['id']);
5331                 $users = [];
5332
5333                 if ($type == "xml") {
5334                         $user_element = "users";
5335                         $k = 0;
5336                         foreach ($members as $member) {
5337                                 $user = api_get_user($a, $member['nurl']);
5338                                 $users[$k++.":user"] = $user;
5339                         }
5340                 } else {
5341                         $user_element = "user";
5342                         foreach ($members as $member) {
5343                                 $user = api_get_user($a, $member['nurl']);
5344                                 $users[] = $user;
5345                         }
5346                 }
5347                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5348         }
5349         return api_format_data("groups", $type, ['group' => $grps]);
5350 }
5351 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5352
5353
5354 /**
5355  * Delete the specified group of the user.
5356  *
5357  * @param string $type Return type (atom, rss, xml, json)
5358  *
5359  * @return array|string
5360  */
5361 function api_friendica_group_delete($type)
5362 {
5363         $a = get_app();
5364
5365         if (api_user() === false) {
5366                 throw new ForbiddenException();
5367         }
5368
5369         // params
5370         $user_info = api_get_user($a);
5371         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5372         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5373         $uid = $user_info['uid'];
5374
5375         // error if no gid specified
5376         if ($gid == 0 || $name == "") {
5377                 throw new BadRequestException('gid or name not specified');
5378         }
5379
5380         // get data of the specified group id
5381         $r = q(
5382                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5383                 intval($uid),
5384                 intval($gid)
5385         );
5386         // error message if specified gid is not in database
5387         if (!DBM::is_result($r)) {
5388                 throw new BadRequestException('gid not available');
5389         }
5390
5391         // get data of the specified group id and group name
5392         $rname = q(
5393                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5394                 intval($uid),
5395                 intval($gid),
5396                 dbesc($name)
5397         );
5398         // error message if specified gid is not in database
5399         if (!DBM::is_result($rname)) {
5400                 throw new BadRequestException('wrong group name');
5401         }
5402
5403         // delete group
5404         $ret = Group::removeByName($uid, $name);
5405         if ($ret) {
5406                 // return success
5407                 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5408                 return api_format_data("group_delete", $type, ['result' => $success]);
5409         } else {
5410                 throw new BadRequestException('other API error');
5411         }
5412 }
5413 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5414
5415
5416 /**
5417  * Create the specified group with the posted array of contacts.
5418  *
5419  * @param string $type Return type (atom, rss, xml, json)
5420  *
5421  * @return array|string
5422  */
5423 function api_friendica_group_create($type)
5424 {
5425         $a = get_app();
5426
5427         if (api_user() === false) {
5428                 throw new ForbiddenException();
5429         }
5430
5431         // params
5432         $user_info = api_get_user($a);
5433         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5434         $uid = $user_info['uid'];
5435         $json = json_decode($_POST['json'], true);
5436         $users = $json['user'];
5437
5438         // error if no name specified
5439         if ($name == "") {
5440                 throw new BadRequestException('group name not specified');
5441         }
5442
5443         // get data of the specified group name
5444         $rname = q(
5445                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5446                 intval($uid),
5447                 dbesc($name)
5448         );
5449         // error message if specified group name already exists
5450         if (DBM::is_result($rname)) {
5451                 throw new BadRequestException('group name already exists');
5452         }
5453
5454         // check if specified group name is a deleted group
5455         $rname = q(
5456                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5457                 intval($uid),
5458                 dbesc($name)
5459         );
5460         // error message if specified group name already exists
5461         if (DBM::is_result($rname)) {
5462                 $reactivate_group = true;
5463         }
5464
5465         // create group
5466         $ret = Group::create($uid, $name);
5467         if ($ret) {
5468                 $gid = Group::getIdByName($uid, $name);
5469         } else {
5470                 throw new BadRequestException('other API error');
5471         }
5472
5473         // add members
5474         $erroraddinguser = false;
5475         $errorusers = [];
5476         foreach ($users as $user) {
5477                 $cid = $user['cid'];
5478                 // check if user really exists as contact
5479                 $contact = q(
5480                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5481                         intval($cid),
5482                         intval($uid)
5483                 );
5484                 if (count($contact)) {
5485                         Group::addMember($gid, $cid);
5486                 } else {
5487                         $erroraddinguser = true;
5488                         $errorusers[] = $cid;
5489                 }
5490         }
5491
5492         // return success message incl. missing users in array
5493         $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5494         $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5495         return api_format_data("group_create", $type, ['result' => $success]);
5496 }
5497 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5498
5499
5500 /**
5501  * Update the specified group with the posted array of contacts.
5502  *
5503  * @param string $type Return type (atom, rss, xml, json)
5504  *
5505  * @return array|string
5506  */
5507 function api_friendica_group_update($type)
5508 {
5509         $a = get_app();
5510
5511         if (api_user() === false) {
5512                 throw new ForbiddenException();
5513         }
5514
5515         // params
5516         $user_info = api_get_user($a);
5517         $uid = $user_info['uid'];
5518         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5519         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5520         $json = json_decode($_POST['json'], true);
5521         $users = $json['user'];
5522
5523         // error if no name specified
5524         if ($name == "") {
5525                 throw new BadRequestException('group name not specified');
5526         }
5527
5528         // error if no gid specified
5529         if ($gid == "") {
5530                 throw new BadRequestException('gid not specified');
5531         }
5532
5533         // remove members
5534         $members = Contact::getByGroupId($gid);
5535         foreach ($members as $member) {
5536                 $cid = $member['id'];
5537                 foreach ($users as $user) {
5538                         $found = ($user['cid'] == $cid ? true : false);
5539                 }
5540                 if (!$found) {
5541                         Group::removeMemberByName($uid, $name, $cid);
5542                 }
5543         }
5544
5545         // add members
5546         $erroraddinguser = false;
5547         $errorusers = [];
5548         foreach ($users as $user) {
5549                 $cid = $user['cid'];
5550                 // check if user really exists as contact
5551                 $contact = q(
5552                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5553                         intval($cid),
5554                         intval($uid)
5555                 );
5556
5557                 if (count($contact)) {
5558                         Group::addMember($gid, $cid);
5559                 } else {
5560                         $erroraddinguser = true;
5561                         $errorusers[] = $cid;
5562                 }
5563         }
5564
5565         // return success message incl. missing users in array
5566         $status = ($erroraddinguser ? "missing user" : "ok");
5567         $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5568         return api_format_data("group_update", $type, ['result' => $success]);
5569 }
5570
5571 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5572
5573 /**
5574  *
5575  * @param string $type Return type (atom, rss, xml, json)
5576  *
5577  * @return array|string
5578  */
5579 function api_friendica_activity($type)
5580 {
5581         $a = get_app();
5582
5583         if (api_user() === false) {
5584                 throw new ForbiddenException();
5585         }
5586         $verb = strtolower($a->argv[3]);
5587         $verb = preg_replace("|\..*$|", "", $verb);
5588
5589         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5590
5591         $res = Item::performLike($id, $verb);
5592
5593         if ($res) {
5594                 if ($type == "xml") {
5595                         $ok = "true";
5596                 } else {
5597                         $ok = "ok";
5598                 }
5599                 return api_format_data('ok', $type, ['ok' => $ok]);
5600         } else {
5601                 throw new BadRequestException('Error adding activity');
5602         }
5603 }
5604
5605 /// @TODO move to top of file or somewhere better
5606 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5607 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5608 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5609 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5610 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5611 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5612 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5613 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5614 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5615 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5616
5617 /**
5618  * @brief Returns notifications
5619  *
5620  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5621  * @return string
5622 */
5623 function api_friendica_notification($type)
5624 {
5625         $a = get_app();
5626
5627         if (api_user() === false) {
5628                 throw new ForbiddenException();
5629         }
5630         if ($a->argc!==3) {
5631                 throw new BadRequestException("Invalid argument count");
5632         }
5633         $nm = new NotificationsManager();
5634
5635         $notes = $nm->getAll([], "+seen -date", 50);
5636
5637         if ($type == "xml") {
5638                 $xmlnotes = [];
5639                 foreach ($notes as $note) {
5640                         $xmlnotes[] = ["@attributes" => $note];
5641                 }
5642
5643                 $notes = $xmlnotes;
5644         }
5645
5646         return api_format_data("notes", $type, ['note' => $notes]);
5647 }
5648
5649 /**
5650  * POST request with 'id' param as notification id
5651  *
5652  * @brief Set notification as seen and returns associated item (if possible)
5653  *
5654  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5655  * @return string
5656  */
5657 function api_friendica_notification_seen($type)
5658 {
5659         $a = get_app();
5660
5661         if (api_user() === false) {
5662                 throw new ForbiddenException();
5663         }
5664         if ($a->argc!==4) {
5665                 throw new BadRequestException("Invalid argument count");
5666         }
5667
5668         $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5669
5670         $nm = new NotificationsManager();
5671         $note = $nm->getByID($id);
5672         if (is_null($note)) {
5673                 throw new BadRequestException("Invalid argument");
5674         }
5675
5676         $nm->setSeen($note);
5677         if ($note['otype']=='item') {
5678                 // would be really better with an ItemsManager and $im->getByID() :-P
5679                 $r = q(
5680                         "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5681                         intval($note['iid']),
5682                         intval(local_user())
5683                 );
5684                 if ($r!==false) {
5685                         // we found the item, return it to the user
5686                         $user_info = api_get_user($a);
5687                         $ret = api_format_items($r, $user_info, false, $type);
5688                         $data = ['status' => $ret];
5689                         return api_format_data("status", $type, $data);
5690                 }
5691                 // the item can't be found, but we set the note as seen, so we count this as a success
5692         }
5693         return api_format_data('result', $type, ['result' => "success"]);
5694 }
5695
5696 /// @TODO move to top of file or somewhere better
5697 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5698 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5699
5700 /**
5701  * @brief update a direct_message to seen state
5702  *
5703  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5704  * @return string (success result=ok, error result=error with error message)
5705  */
5706 function api_friendica_direct_messages_setseen($type)
5707 {
5708         $a = get_app();
5709         if (api_user() === false) {
5710                 throw new ForbiddenException();
5711         }
5712
5713         // params
5714         $user_info = api_get_user($a);
5715         $uid = $user_info['uid'];
5716         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5717
5718         // return error if id is zero
5719         if ($id == "") {
5720                 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5721                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5722         }
5723
5724         // get data of the specified message id
5725         $r = q(
5726                 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5727                 intval($id),
5728                 intval($uid)
5729         );
5730
5731         // error message if specified id is not in database
5732         if (!DBM::is_result($r)) {
5733                 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5734                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5735         }
5736
5737         // update seen indicator
5738         $result = q(
5739                 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5740                 intval($id),
5741                 intval($uid)
5742         );
5743
5744         if ($result) {
5745                 // return success
5746                 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5747                 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5748         } else {
5749                 $answer = ['result' => 'error', 'message' => 'unknown error'];
5750                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5751         }
5752 }
5753
5754 /// @TODO move to top of file or somewhere better
5755 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5756
5757 /**
5758  * @brief search for direct_messages containing a searchstring through api
5759  *
5760  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5761  * @return string (success: success=true if found and search_result contains found messages,
5762  *                          success=false if nothing was found, search_result='nothing found',
5763  *                 error: result=error with error message)
5764  */
5765 function api_friendica_direct_messages_search($type)
5766 {
5767         $a = get_app();
5768
5769         if (api_user() === false) {
5770                 throw new ForbiddenException();
5771         }
5772
5773         // params
5774         $user_info = api_get_user($a);
5775         $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5776         $uid = $user_info['uid'];
5777
5778         // error if no searchstring specified
5779         if ($searchstring == "") {
5780                 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5781                 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5782         }
5783
5784         // get data for the specified searchstring
5785         $r = q(
5786                 "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",
5787                 intval($uid),
5788                 dbesc('%'.$searchstring.'%')
5789         );
5790
5791         $profile_url = $user_info["url"];
5792
5793         // message if nothing was found
5794         if (!DBM::is_result($r)) {
5795                 $success = ['success' => false, 'search_results' => 'problem with query'];
5796         } elseif (count($r) == 0) {
5797                 $success = ['success' => false, 'search_results' => 'nothing found'];
5798         } else {
5799                 $ret = [];
5800                 foreach ($r as $item) {
5801                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
5802                                 $recipient = $user_info;
5803                                 $sender = api_get_user($a, normalise_link($item['contact-url']));
5804                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5805                                 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5806                                 $sender = $user_info;
5807                         }
5808
5809                         $ret[] = api_format_messages($item, $recipient, $sender);
5810                 }
5811                 $success = ['success' => true, 'search_results' => $ret];
5812         }
5813
5814         return api_format_data("direct_message_search", $type, ['$result' => $success]);
5815 }
5816
5817 /// @TODO move to top of file or somewhere better
5818 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5819
5820 /**
5821  * @brief return data of all the profiles a user has to the client
5822  *
5823  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5824  * @return string
5825  */
5826 function api_friendica_profile_show($type)
5827 {
5828         $a = get_app();
5829
5830         if (api_user() === false) {
5831                 throw new ForbiddenException();
5832         }
5833
5834         // input params
5835         $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5836
5837         // retrieve general information about profiles for user
5838         $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5839         $directory = Config::get('system', 'directory');
5840
5841         // get data of the specified profile id or all profiles of the user if not specified
5842         if ($profileid != 0) {
5843                 $r = q(
5844                         "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5845                         intval(api_user()),
5846                         intval($profileid)
5847                 );
5848
5849                 // error message if specified gid is not in database
5850                 if (!DBM::is_result($r)) {
5851                         throw new BadRequestException("profile_id not available");
5852                 }
5853         } else {
5854                 $r = q(
5855                         "SELECT * FROM `profile` WHERE `uid` = %d",
5856                         intval(api_user())
5857                 );
5858         }
5859         // loop through all returned profiles and retrieve data and users
5860         $k = 0;
5861         foreach ($r as $rr) {
5862                 $profile = api_format_items_profiles($rr);
5863
5864                 // select all users from contact table, loop and prepare standard return for user data
5865                 $users = [];
5866                 $r = q(
5867                         "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5868                         intval(api_user()),
5869                         intval($rr['profile_id'])
5870                 );
5871
5872                 foreach ($r as $rr) {
5873                         $user = api_get_user($a, $rr['nurl']);
5874                         ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5875                 }
5876                 $profile['users'] = $users;
5877
5878                 // add prepared profile data to array for final return
5879                 if ($type == "xml") {
5880                         $profiles[$k++ . ":profile"] = $profile;
5881                 } else {
5882                         $profiles[] = $profile;
5883                 }
5884         }
5885
5886         // return settings, authenticated user and profiles data
5887         $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5888
5889         $result = ['multi_profiles' => $multi_profiles ? true : false,
5890                                         'global_dir' => $directory,
5891                                         'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5892                                         'profiles' => $profiles];
5893         return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5894 }
5895 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5896
5897 /**
5898  * Returns a list of saved searches.
5899  *
5900  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5901  *
5902  * @param  string $type Return format: json or xml
5903  *
5904  * @return string|array
5905  */
5906 function api_saved_searches_list($type)
5907 {
5908         $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5909
5910         $result = [];
5911         while ($term = $terms->fetch()) {
5912                 $result[] = [
5913                         'name' => $term['term'],
5914                         'query' => $term['term'],
5915                         'id_str' => $term['id'],
5916                         'id' => intval($term['id'])
5917                 ];
5918         }
5919
5920         dba::close($terms);
5921
5922         return api_format_data("terms", $type, ['terms' => $result]);
5923 }
5924
5925 /// @TODO move to top of file or somewhere better
5926 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5927
5928 /*
5929 @TODO Maybe open to implement?
5930 To.Do:
5931         [pagename] => api/1.1/statuses/lookup.json
5932         [id] => 605138389168451584
5933         [include_cards] => true
5934         [cards_platform] => Android-12
5935         [include_entities] => true
5936         [include_my_retweet] => 1
5937         [include_rts] => 1
5938         [include_reply_count] => true
5939         [include_descendent_reply_count] => true
5940 (?)
5941
5942
5943 Not implemented by now:
5944 statuses/retweets_of_me
5945 friendships/create
5946 friendships/destroy
5947 friendships/exists
5948 friendships/show
5949 account/update_location
5950 account/update_profile_background_image
5951 blocks/create
5952 blocks/destroy
5953 friendica/profile/update
5954 friendica/profile/create
5955 friendica/profile/delete
5956
5957 Not implemented in status.net:
5958 statuses/retweeted_to_me
5959 statuses/retweeted_by_me
5960 direct_messages/destroy
5961 account/end_session
5962 account/update_delivery_device
5963 notifications/follow
5964 notifications/leave
5965 blocks/exists
5966 blocks/blocking
5967 lists
5968 */