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