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