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