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