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