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