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