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