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