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