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