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