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