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