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