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