]> git.mxchange.org Git - friendica.git/blob - include/api.php
af71e2f1cf2693eda373c45167c385106f2fdb9c
[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::select(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::select(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::selectThread(api_user(), [], $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::select(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::selectThread(api_user(), [], $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::select(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::select(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(api_user(), $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::select(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::select(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::selectFirst(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::select(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::select(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         $user_info = api_get_user($a);
3704
3705         if (api_user() === false || $user_info === false) {
3706                 throw new ForbiddenException();
3707         }
3708
3709         // params
3710         $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3711         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3712         if ($page < 0) {
3713                 $page = 0;
3714         }
3715
3716         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3717         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3718
3719         $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3720         $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3721
3722         //  caller user info
3723         unset($_REQUEST["user_id"]);
3724         unset($_GET["user_id"]);
3725
3726         unset($_REQUEST["screen_name"]);
3727         unset($_GET["screen_name"]);
3728
3729         $profile_url = $user_info["url"];
3730
3731         // pagination
3732         $start = $page * $count;
3733
3734         $sql_extra = "";
3735
3736         // filters
3737         if ($box=="sentbox") {
3738                 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3739         } elseif ($box == "conversation") {
3740                 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"])  . "'";
3741         } elseif ($box == "all") {
3742                 $sql_extra = "true";
3743         } elseif ($box == "inbox") {
3744                 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3745         }
3746
3747         if ($max_id > 0) {
3748                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3749         }
3750
3751         if ($user_id != "") {
3752                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3753         } elseif ($screen_name !="") {
3754                 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3755         }
3756
3757         $r = q(
3758                 "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",
3759                 intval(api_user()),
3760                 intval($since_id),
3761                 intval($start),
3762                 intval($count)
3763         );
3764         if ($verbose == "true" && !DBM::is_result($r)) {
3765                 $answer = ['result' => 'error', 'message' => 'no mails available'];
3766                 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3767         }
3768
3769         $ret = [];
3770         foreach ($r as $item) {
3771                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3772                         $recipient = $user_info;
3773                         $sender = api_get_user($a, normalise_link($item['contact-url']));
3774                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3775                         $recipient = api_get_user($a, normalise_link($item['contact-url']));
3776                         $sender = $user_info;
3777                 }
3778
3779                 if (isset($recipient) && isset($sender)) {
3780                         $ret[] = api_format_messages($item, $recipient, $sender);
3781                 }
3782         }
3783
3784
3785         $data = ['direct_message' => $ret];
3786         switch ($type) {
3787                 case "atom":
3788                 case "rss":
3789                         $data = api_rss_extra($a, $data, $user_info);
3790         }
3791
3792         return api_format_data("direct-messages", $type, $data);
3793 }
3794
3795 /**
3796  * Returns the most recent direct messages sent by the user.
3797  *
3798  * @param string $type Return type (atom, rss, xml, json)
3799  *
3800  * @return array|string
3801  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3802  */
3803 function api_direct_messages_sentbox($type)
3804 {
3805         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3806         return api_direct_messages_box($type, "sentbox", $verbose);
3807 }
3808
3809 /**
3810  * Returns the most recent direct messages sent to the user.
3811  *
3812  * @param string $type Return type (atom, rss, xml, json)
3813  *
3814  * @return array|string
3815  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3816  */
3817 function api_direct_messages_inbox($type)
3818 {
3819         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3820         return api_direct_messages_box($type, "inbox", $verbose);
3821 }
3822
3823 /**
3824  *
3825  * @param string $type Return type (atom, rss, xml, json)
3826  *
3827  * @return array|string
3828  */
3829 function api_direct_messages_all($type)
3830 {
3831         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3832         return api_direct_messages_box($type, "all", $verbose);
3833 }
3834
3835 /**
3836  *
3837  * @param string $type Return type (atom, rss, xml, json)
3838  *
3839  * @return array|string
3840  */
3841 function api_direct_messages_conversation($type)
3842 {
3843         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3844         return api_direct_messages_box($type, "conversation", $verbose);
3845 }
3846
3847 /// @TODO move to top of file or somewhere better
3848 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3849 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3850 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3851 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3852
3853 /**
3854  * Returns an OAuth Request Token.
3855  *
3856  * @see https://oauth.net/core/1.0/#auth_step1
3857  */
3858 function api_oauth_request_token()
3859 {
3860         $oauth1 = new FKOAuth1();
3861         try {
3862                 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3863         } catch (Exception $e) {
3864                 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3865                 killme();
3866         }
3867         echo $r;
3868         killme();
3869 }
3870
3871 /**
3872  * Returns an OAuth Access Token.
3873  *
3874  * @return array|string
3875  * @see https://oauth.net/core/1.0/#auth_step3
3876  */
3877 function api_oauth_access_token()
3878 {
3879         $oauth1 = new FKOAuth1();
3880         try {
3881                 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3882         } catch (Exception $e) {
3883                 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3884                 killme();
3885         }
3886         echo $r;
3887         killme();
3888 }
3889
3890 /// @TODO move to top of file or somewhere better
3891 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3892 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3893
3894
3895 /**
3896  * @brief delete a complete photoalbum with all containing photos from database through api
3897  *
3898  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3899  * @return string|array
3900  */
3901 function api_fr_photoalbum_delete($type)
3902 {
3903         if (api_user() === false) {
3904                 throw new ForbiddenException();
3905         }
3906         // input params
3907         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3908
3909         // we do not allow calls without album string
3910         if ($album == "") {
3911                 throw new BadRequestException("no albumname specified");
3912         }
3913         // check if album is existing
3914         $r = q(
3915                 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3916                 intval(api_user()),
3917                 dbesc($album)
3918         );
3919         if (!DBM::is_result($r)) {
3920                 throw new BadRequestException("album not available");
3921         }
3922
3923         // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3924         // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3925         foreach ($r as $rr) {
3926                 $photo_item = q(
3927                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3928                         intval(local_user()),
3929                         dbesc($rr['resource-id'])
3930                 );
3931
3932                 if (!DBM::is_result($photo_item)) {
3933                         throw new InternalServerErrorException("problem with deleting items occured");
3934                 }
3935                 Item::deleteForUser(['id' => $photo_item[0]['id']], api_user());
3936         }
3937
3938         // now let's delete all photos from the album
3939         $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
3940
3941         // return success of deletion or error message
3942         if ($result) {
3943                 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
3944                 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
3945         } else {
3946                 throw new InternalServerErrorException("unknown error - deleting from database failed");
3947         }
3948 }
3949
3950 /**
3951  * @brief update the name of the album for all photos of an album
3952  *
3953  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3954  * @return string|array
3955  */
3956 function api_fr_photoalbum_update($type)
3957 {
3958         if (api_user() === false) {
3959                 throw new ForbiddenException();
3960         }
3961         // input params
3962         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3963         $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3964
3965         // we do not allow calls without album string
3966         if ($album == "") {
3967                 throw new BadRequestException("no albumname specified");
3968         }
3969         if ($album_new == "") {
3970                 throw new BadRequestException("no new albumname specified");
3971         }
3972         // check if album is existing
3973         if (!dba::exists('photo', ['uid' => api_user(), 'album' => $album])) {
3974                 throw new BadRequestException("album not available");
3975         }
3976         // now let's update all photos to the albumname
3977         $result = dba::update('photo', ['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
3978
3979         // return success of updating or error message
3980         if ($result) {
3981                 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
3982                 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
3983         } else {
3984                 throw new InternalServerErrorException("unknown error - updating in database failed");
3985         }
3986 }
3987
3988
3989 /**
3990  * @brief list all photos of the authenticated user
3991  *
3992  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3993  * @return string|array
3994  */
3995 function api_fr_photos_list($type)
3996 {
3997         if (api_user() === false) {
3998                 throw new ForbiddenException();
3999         }
4000         $r = q(
4001                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4002                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4003                 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4004                 intval(local_user())
4005         );
4006         $typetoext = [
4007                 'image/jpeg' => 'jpg',
4008                 'image/png' => 'png',
4009                 'image/gif' => 'gif'
4010         ];
4011         $data = ['photo'=>[]];
4012         if (DBM::is_result($r)) {
4013                 foreach ($r as $rr) {
4014                         $photo = [];
4015                         $photo['id'] = $rr['resource-id'];
4016                         $photo['album'] = $rr['album'];
4017                         $photo['filename'] = $rr['filename'];
4018                         $photo['type'] = $rr['type'];
4019                         $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4020                         $photo['created'] = $rr['created'];
4021                         $photo['edited'] = $rr['edited'];
4022                         $photo['desc'] = $rr['desc'];
4023
4024                         if ($type == "xml") {
4025                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4026                         } else {
4027                                 $photo['thumb'] = $thumb;
4028                                 $data['photo'][] = $photo;
4029                         }
4030                 }
4031         }
4032         return api_format_data("photos", $type, $data);
4033 }
4034
4035 /**
4036  * @brief upload a new photo or change an existing photo
4037  *
4038  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4039  * @return string|array
4040  */
4041 function api_fr_photo_create_update($type)
4042 {
4043         if (api_user() === false) {
4044                 throw new ForbiddenException();
4045         }
4046         // input params
4047         $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4048         $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4049         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4050         $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4051         $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4052         $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4053         $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4054         $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4055         $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4056
4057         // do several checks on input parameters
4058         // we do not allow calls without album string
4059         if ($album == null) {
4060                 throw new BadRequestException("no albumname specified");
4061         }
4062         // if photo_id == null --> we are uploading a new photo
4063         if ($photo_id == null) {
4064                 $mode = "create";
4065
4066                 // error if no media posted in create-mode
4067                 if (!x($_FILES, 'media')) {
4068                         // Output error
4069                         throw new BadRequestException("no media data submitted");
4070                 }
4071
4072                 // album_new will be ignored in create-mode
4073                 $album_new = "";
4074         } else {
4075                 $mode = "update";
4076
4077                 // check if photo is existing in database
4078                 $r = q(
4079                         "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4080                         intval(api_user()),
4081                         dbesc($photo_id),
4082                         dbesc($album)
4083                 );
4084                 if (!DBM::is_result($r)) {
4085                         throw new BadRequestException("photo not available");
4086                 }
4087         }
4088
4089         // checks on acl strings provided by clients
4090         $acl_input_error = false;
4091         $acl_input_error |= check_acl_input($allow_cid);
4092         $acl_input_error |= check_acl_input($deny_cid);
4093         $acl_input_error |= check_acl_input($allow_gid);
4094         $acl_input_error |= check_acl_input($deny_gid);
4095         if ($acl_input_error) {
4096                 throw new BadRequestException("acl data invalid");
4097         }
4098         // now let's upload the new media in create-mode
4099         if ($mode == "create") {
4100                 $media = $_FILES['media'];
4101                 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4102
4103                 // return success of updating or error message
4104                 if (!is_null($data)) {
4105                         return api_format_data("photo_create", $type, $data);
4106                 } else {
4107                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4108                 }
4109         }
4110
4111         // now let's do the changes in update-mode
4112         if ($mode == "update") {
4113                 $sql_extra = "";
4114
4115                 if (!is_null($desc)) {
4116                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4117                 }
4118
4119                 if (!is_null($album_new)) {
4120                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4121                 }
4122
4123                 if (!is_null($allow_cid)) {
4124                         $allow_cid = trim($allow_cid);
4125                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4126                 }
4127
4128                 if (!is_null($deny_cid)) {
4129                         $deny_cid = trim($deny_cid);
4130                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4131                 }
4132
4133                 if (!is_null($allow_gid)) {
4134                         $allow_gid = trim($allow_gid);
4135                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4136                 }
4137
4138                 if (!is_null($deny_gid)) {
4139                         $deny_gid = trim($deny_gid);
4140                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4141                 }
4142
4143                 $result = false;
4144                 if ($sql_extra != "") {
4145                         $nothingtodo = false;
4146                         $result = q(
4147                                 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4148                                 $sql_extra,
4149                                 DateTimeFormat::utcNow(),   // update edited timestamp
4150                                 intval(api_user()),
4151                                 dbesc($photo_id),
4152                                 dbesc($album)
4153                         );
4154                 } else {
4155                         $nothingtodo = true;
4156                 }
4157
4158                 if (x($_FILES, 'media')) {
4159                         $nothingtodo = false;
4160                         $media = $_FILES['media'];
4161                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4162                         if (!is_null($data)) {
4163                                 return api_format_data("photo_update", $type, $data);
4164                         }
4165                 }
4166
4167                 // return success of updating or error message
4168                 if ($result) {
4169                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4170                         return api_format_data("photo_update", $type, ['$result' => $answer]);
4171                 } else {
4172                         if ($nothingtodo) {
4173                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4174                                 return api_format_data("photo_update", $type, ['$result' => $answer]);
4175                         }
4176                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4177                 }
4178         }
4179         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4180 }
4181
4182 /**
4183  * @brief delete a single photo from the database through api
4184  *
4185  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4186  * @return string|array
4187  */
4188 function api_fr_photo_delete($type)
4189 {
4190         if (api_user() === false) {
4191                 throw new ForbiddenException();
4192         }
4193         // input params
4194         $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4195
4196         // do several checks on input parameters
4197         // we do not allow calls without photo id
4198         if ($photo_id == null) {
4199                 throw new BadRequestException("no photo_id specified");
4200         }
4201         // check if photo is existing in database
4202         $r = q(
4203                 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4204                 intval(api_user()),
4205                 dbesc($photo_id)
4206         );
4207         if (!DBM::is_result($r)) {
4208                 throw new BadRequestException("photo not available");
4209         }
4210         // now we can perform on the deletion of the photo
4211         $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4212
4213         // return success of deletion or error message
4214         if ($result) {
4215                 // retrieve the id of the parent element (the photo element)
4216                 $photo_item = q(
4217                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4218                         intval(local_user()),
4219                         dbesc($photo_id)
4220                 );
4221
4222                 if (!DBM::is_result($photo_item)) {
4223                         throw new InternalServerErrorException("problem with deleting items occured");
4224                 }
4225                 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4226                 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4227                 Item::deleteForUser(['id' => $photo_item[0]['id']], api_user());
4228
4229                 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4230                 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4231         } else {
4232                 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4233         }
4234 }
4235
4236
4237 /**
4238  * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4239  *
4240  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4241  * @return string|array
4242  */
4243 function api_fr_photo_detail($type)
4244 {
4245         if (api_user() === false) {
4246                 throw new ForbiddenException();
4247         }
4248         if (!x($_REQUEST, 'photo_id')) {
4249                 throw new BadRequestException("No photo id.");
4250         }
4251
4252         $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4253         $photo_id = $_REQUEST['photo_id'];
4254
4255         // prepare json/xml output with data from database for the requested photo
4256         $data = prepare_photo_data($type, $scale, $photo_id);
4257
4258         return api_format_data("photo_detail", $type, $data);
4259 }
4260
4261
4262 /**
4263  * Updates the user’s profile image.
4264  *
4265  * @brief updates the profile image for the user (either a specified profile or the default profile)
4266  *
4267  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4268  *
4269  * @return string|array
4270  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4271  */
4272 function api_account_update_profile_image($type)
4273 {
4274         if (api_user() === false) {
4275                 throw new ForbiddenException();
4276         }
4277         // input params
4278         $profile_id = defaults($_REQUEST, 'profile_id', 0);
4279
4280         // error if image data is missing
4281         if (!x($_FILES, 'image')) {
4282                 throw new BadRequestException("no media data submitted");
4283         }
4284
4285         // check if specified profile id is valid
4286         if ($profile_id != 0) {
4287                 $profile = dba::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4288                 // error message if specified profile id is not in database
4289                 if (!DBM::is_result($profile)) {
4290                         throw new BadRequestException("profile_id not available");
4291                 }
4292                 $is_default_profile = $profile['is-default'];
4293         } else {
4294                 $is_default_profile = 1;
4295         }
4296
4297         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4298         $media = null;
4299         if (x($_FILES, 'image')) {
4300                 $media = $_FILES['image'];
4301         } elseif (x($_FILES, 'media')) {
4302                 $media = $_FILES['media'];
4303         }
4304         // save new profile image
4305         $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4306
4307         // get filetype
4308         if (is_array($media['type'])) {
4309                 $filetype = $media['type'][0];
4310         } else {
4311                 $filetype = $media['type'];
4312         }
4313         if ($filetype == "image/jpeg") {
4314                 $fileext = "jpg";
4315         } elseif ($filetype == "image/png") {
4316                 $fileext = "png";
4317         } else {
4318                 throw new InternalServerErrorException('Unsupported filetype');
4319         }
4320
4321         // change specified profile or all profiles to the new resource-id
4322         if ($is_default_profile) {
4323                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4324                 dba::update('photo', ['profile' => false], $condition);
4325         } else {
4326                 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4327                         'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4328                 dba::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4329         }
4330
4331         Contact::updateSelfFromUserID(api_user(), true);
4332
4333         // Update global directory in background
4334         $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4335         if ($url && strlen(Config::get('system', 'directory'))) {
4336                 Worker::add(PRIORITY_LOW, "Directory", $url);
4337         }
4338
4339         Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4340
4341         // output for client
4342         if ($data) {
4343                 return api_account_verify_credentials($type);
4344         } else {
4345                 // SaveMediaToDatabase failed for some reason
4346                 throw new InternalServerErrorException("image upload failed");
4347         }
4348 }
4349
4350 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4351 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4352 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4353 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4354 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4355 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4356 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4357 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4358 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4359
4360 /**
4361  * Update user profile
4362  *
4363  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4364  *
4365  * @return array|string
4366  */
4367 function api_account_update_profile($type)
4368 {
4369         $local_user = api_user();
4370         $api_user = api_get_user(get_app());
4371
4372         if (!empty($_POST['name'])) {
4373                 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4374                 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4375                 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4376                 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4377         }
4378
4379         if (isset($_POST['description'])) {
4380                 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4381                 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4382                 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4383         }
4384
4385         Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4386         // Update global directory in background
4387         if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4388                 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4389         }
4390
4391         return api_account_verify_credentials($type);
4392 }
4393
4394 /// @TODO move to top of file or somewhere better
4395 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4396
4397 /**
4398  *
4399  * @param string $acl_string
4400  */
4401 function check_acl_input($acl_string)
4402 {
4403         if ($acl_string == null || $acl_string == " ") {
4404                 return false;
4405         }
4406         $contact_not_found = false;
4407
4408         // split <x><y><z> into array of cid's
4409         preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4410
4411         // check for each cid if it is available on server
4412         $cid_array = $array[0];
4413         foreach ($cid_array as $cid) {
4414                 $cid = str_replace("<", "", $cid);
4415                 $cid = str_replace(">", "", $cid);
4416                 $contact = q(
4417                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4418                         intval($cid),
4419                         intval(api_user())
4420                 );
4421                 $contact_not_found |= !DBM::is_result($contact);
4422         }
4423         return $contact_not_found;
4424 }
4425
4426 /**
4427  *
4428  * @param string  $mediatype
4429  * @param array   $media
4430  * @param string  $type
4431  * @param string  $album
4432  * @param string  $allow_cid
4433  * @param string  $deny_cid
4434  * @param string  $allow_gid
4435  * @param string  $deny_gid
4436  * @param string  $desc
4437  * @param integer $profile
4438  * @param boolean $visibility
4439  * @param string  $photo_id
4440  */
4441 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)
4442 {
4443         $visitor   = 0;
4444         $src = "";
4445         $filetype = "";
4446         $filename = "";
4447         $filesize = 0;
4448
4449         if (is_array($media)) {
4450                 if (is_array($media['tmp_name'])) {
4451                         $src = $media['tmp_name'][0];
4452                 } else {
4453                         $src = $media['tmp_name'];
4454                 }
4455                 if (is_array($media['name'])) {
4456                         $filename = basename($media['name'][0]);
4457                 } else {
4458                         $filename = basename($media['name']);
4459                 }
4460                 if (is_array($media['size'])) {
4461                         $filesize = intval($media['size'][0]);
4462                 } else {
4463                         $filesize = intval($media['size']);
4464                 }
4465                 if (is_array($media['type'])) {
4466                         $filetype = $media['type'][0];
4467                 } else {
4468                         $filetype = $media['type'];
4469                 }
4470         }
4471
4472         if ($filetype == "") {
4473                 $filetype=Image::guessType($filename);
4474         }
4475         $imagedata = getimagesize($src);
4476         if ($imagedata) {
4477                 $filetype = $imagedata['mime'];
4478         }
4479         logger(
4480                 "File upload src: " . $src . " - filename: " . $filename .
4481                 " - size: " . $filesize . " - type: " . $filetype,
4482                 LOGGER_DEBUG
4483         );
4484
4485         // check if there was a php upload error
4486         if ($filesize == 0 && $media['error'] == 1) {
4487                 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4488         }
4489         // check against max upload size within Friendica instance
4490         $maximagesize = Config::get('system', 'maximagesize');
4491         if ($maximagesize && ($filesize > $maximagesize)) {
4492                 $formattedBytes = formatBytes($maximagesize);
4493                 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4494         }
4495
4496         // create Photo instance with the data of the image
4497         $imagedata = @file_get_contents($src);
4498         $Image = new Image($imagedata, $filetype);
4499         if (! $Image->isValid()) {
4500                 throw new InternalServerErrorException("unable to process image data");
4501         }
4502
4503         // check orientation of image
4504         $Image->orient($src);
4505         @unlink($src);
4506
4507         // check max length of images on server
4508         $max_length = Config::get('system', 'max_image_length');
4509         if (! $max_length) {
4510                 $max_length = MAX_IMAGE_LENGTH;
4511         }
4512         if ($max_length > 0) {
4513                 $Image->scaleDown($max_length);
4514                 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4515         }
4516         $width = $Image->getWidth();
4517         $height = $Image->getHeight();
4518
4519         // create a new resource-id if not already provided
4520         $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4521
4522         if ($mediatype == "photo") {
4523                 // upload normal image (scales 0, 1, 2)
4524                 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4525
4526                 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4527                 if (! $r) {
4528                         logger("photo upload: image upload with scale 0 (original size) failed");
4529                 }
4530                 if ($width > 640 || $height > 640) {
4531                         $Image->scaleDown(640);
4532                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4533                         if (! $r) {
4534                                 logger("photo upload: image upload with scale 1 (640x640) failed");
4535                         }
4536                 }
4537
4538                 if ($width > 320 || $height > 320) {
4539                         $Image->scaleDown(320);
4540                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4541                         if (! $r) {
4542                                 logger("photo upload: image upload with scale 2 (320x320) failed");
4543                         }
4544                 }
4545                 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4546         } elseif ($mediatype == "profileimage") {
4547                 // upload profile image (scales 4, 5, 6)
4548                 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4549
4550                 if ($width > 175 || $height > 175) {
4551                         $Image->scaleDown(175);
4552                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4553                         if (! $r) {
4554                                 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4555                         }
4556                 }
4557
4558                 if ($width > 80 || $height > 80) {
4559                         $Image->scaleDown(80);
4560                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4561                         if (! $r) {
4562                                 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4563                         }
4564                 }
4565
4566                 if ($width > 48 || $height > 48) {
4567                         $Image->scaleDown(48);
4568                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4569                         if (! $r) {
4570                                 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4571                         }
4572                 }
4573                 $Image->__destruct();
4574                 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4575         }
4576
4577         if (isset($r) && $r) {
4578                 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4579                 if ($photo_id == null && $mediatype == "photo") {
4580                         post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4581                 }
4582                 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4583                 return prepare_photo_data($type, false, $hash);
4584         } else {
4585                 throw new InternalServerErrorException("image upload failed");
4586         }
4587 }
4588
4589 /**
4590  *
4591  * @param string  $hash
4592  * @param string  $allow_cid
4593  * @param string  $deny_cid
4594  * @param string  $allow_gid
4595  * @param string  $deny_gid
4596  * @param string  $filetype
4597  * @param boolean $visibility
4598  */
4599 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4600 {
4601         // get data about the api authenticated user
4602         $uri = Item::newURI(intval(api_user()));
4603         $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4604
4605         $arr = [];
4606         $arr['guid']          = get_guid(32);
4607         $arr['uid']           = intval(api_user());
4608         $arr['uri']           = $uri;
4609         $arr['parent-uri']    = $uri;
4610         $arr['type']          = 'photo';
4611         $arr['wall']          = 1;
4612         $arr['resource-id']   = $hash;
4613         $arr['contact-id']    = $owner_record[0]['id'];
4614         $arr['owner-name']    = $owner_record[0]['name'];
4615         $arr['owner-link']    = $owner_record[0]['url'];
4616         $arr['owner-avatar']  = $owner_record[0]['thumb'];
4617         $arr['author-name']   = $owner_record[0]['name'];
4618         $arr['author-link']   = $owner_record[0]['url'];
4619         $arr['author-avatar'] = $owner_record[0]['thumb'];
4620         $arr['title']         = "";
4621         $arr['allow_cid']     = $allow_cid;
4622         $arr['allow_gid']     = $allow_gid;
4623         $arr['deny_cid']      = $deny_cid;
4624         $arr['deny_gid']      = $deny_gid;
4625         $arr['visible']       = $visibility;
4626         $arr['origin']        = 1;
4627
4628         $typetoext = [
4629                         'image/jpeg' => 'jpg',
4630                         'image/png' => 'png',
4631                         'image/gif' => 'gif'
4632                         ];
4633
4634         // adds link to the thumbnail scale photo
4635         $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4636                                 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4637                                 . '[/url]';
4638
4639         // do the magic for storing the item in the database and trigger the federation to other contacts
4640         Item::insert($arr);
4641 }
4642
4643 /**
4644  *
4645  * @param string $type
4646  * @param int    $scale
4647  * @param string $photo_id
4648  *
4649  * @return array
4650  */
4651 function prepare_photo_data($type, $scale, $photo_id)
4652 {
4653         $a = get_app();
4654         $user_info = api_get_user($a);
4655
4656         if ($user_info === false) {
4657                 throw new ForbiddenException();
4658         }
4659
4660         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4661         $data_sql = ($scale === false ? "" : "data, ");
4662
4663         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4664         // clients needs to convert this in their way for further processing
4665         $r = q(
4666                 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4667                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4668                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4669                         FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4670                 $data_sql,
4671                 intval(local_user()),
4672                 dbesc($photo_id),
4673                 $scale_sql
4674         );
4675
4676         $typetoext = [
4677                 'image/jpeg' => 'jpg',
4678                 'image/png' => 'png',
4679                 'image/gif' => 'gif'
4680         ];
4681
4682         // prepare output data for photo
4683         if (DBM::is_result($r)) {
4684                 $data = ['photo' => $r[0]];
4685                 $data['photo']['id'] = $data['photo']['resource-id'];
4686                 if ($scale !== false) {
4687                         $data['photo']['data'] = base64_encode($data['photo']['data']);
4688                 } else {
4689                         unset($data['photo']['datasize']); //needed only with scale param
4690                 }
4691                 if ($type == "xml") {
4692                         $data['photo']['links'] = [];
4693                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4694                                 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4695                                                                                 "scale" => $k,
4696                                                                                 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4697                         }
4698                 } else {
4699                         $data['photo']['link'] = [];
4700                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4701                         $i = 0;
4702                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4703                                 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4704                                 $i++;
4705                         }
4706                 }
4707                 unset($data['photo']['resource-id']);
4708                 unset($data['photo']['minscale']);
4709                 unset($data['photo']['maxscale']);
4710         } else {
4711                 throw new NotFoundException();
4712         }
4713
4714         // retrieve item element for getting activities (like, dislike etc.) related to photo
4715         $item = q(
4716                 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4717                 intval(local_user()),
4718                 dbesc($photo_id)
4719         );
4720         $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4721
4722         // retrieve comments on photo
4723         $condition = ["`parent` = ? AND `uid` = ? AND (`verb` = ? OR `type`='photo')",
4724                 $item[0]['parent'], api_user(), ACTIVITY_POST];
4725
4726         $statuses = Item::select(api_user(), [], $condition);
4727
4728         // prepare output of comments
4729         $commentData = api_format_items(dba::inArray($statuses), $user_info, false, $type);
4730         $comments = [];
4731         if ($type == "xml") {
4732                 $k = 0;
4733                 foreach ($commentData as $comment) {
4734                         $comments[$k++ . ":comment"] = $comment;
4735                 }
4736         } else {
4737                 foreach ($commentData as $comment) {
4738                         $comments[] = $comment;
4739                 }
4740         }
4741         $data['photo']['friendica_comments'] = $comments;
4742
4743         // include info if rights on photo and rights on item are mismatching
4744         $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4745                 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4746                 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4747                 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4748         $data['photo']['rights_mismatch'] = $rights_mismatch;
4749
4750         return $data;
4751 }
4752
4753
4754 /**
4755  * Similar as /mod/redir.php
4756  * redirect to 'url' after dfrn auth
4757  *
4758  * Why this when there is mod/redir.php already?
4759  * This use api_user() and api_login()
4760  *
4761  * params
4762  *              c_url: url of remote contact to auth to
4763  *              url: string, url to redirect after auth
4764  */
4765 function api_friendica_remoteauth()
4766 {
4767         $url = (x($_GET, 'url') ? $_GET['url'] : '');
4768         $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4769
4770         if ($url === '' || $c_url === '') {
4771                 throw new BadRequestException("Wrong parameters.");
4772         }
4773
4774         $c_url = normalise_link($c_url);
4775
4776         // traditional DFRN
4777
4778         $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4779
4780         if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4781                 throw new BadRequestException("Unknown contact");
4782         }
4783
4784         $cid = $contact['id'];
4785
4786         $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4787
4788         if ($contact['duplex'] && $contact['issued-id']) {
4789                 $orig_id = $contact['issued-id'];
4790                 $dfrn_id = '1:' . $orig_id;
4791         }
4792         if ($contact['duplex'] && $contact['dfrn-id']) {
4793                 $orig_id = $contact['dfrn-id'];
4794                 $dfrn_id = '0:' . $orig_id;
4795         }
4796
4797         $sec = random_string();
4798
4799         $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4800                 'sec' => $sec, 'expire' => time() + 45];
4801         dba::insert('profile_check', $fields);
4802
4803         logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4804         $dest = ($url ? '&destination_url=' . $url : '');
4805         goaway(
4806                 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4807                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4808                 . '&type=profile&sec=' . $sec . $dest
4809         );
4810 }
4811 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4812
4813 /**
4814  * @brief Return the item shared, if the item contains only the [share] tag
4815  *
4816  * @param array $item Sharer item
4817  * @return array|false Shared item or false if not a reshare
4818  */
4819 function api_share_as_retweet(&$item)
4820 {
4821         $body = trim($item["body"]);
4822
4823         if (Diaspora::isReshare($body, false)===false) {
4824                 return false;
4825         }
4826
4827         /// @TODO "$1" should maybe mean '$1' ?
4828         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4829         /*
4830                 * Skip if there is no shared message in there
4831                 * we already checked this in diaspora::isReshare()
4832                 * but better one more than one less...
4833                 */
4834         if ($body == $attributes) {
4835                 return false;
4836         }
4837
4838
4839         // build the fake reshared item
4840         $reshared_item = $item;
4841
4842         $author = "";
4843         preg_match("/author='(.*?)'/ism", $attributes, $matches);
4844         if ($matches[1] != "") {
4845                 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4846         }
4847
4848         preg_match('/author="(.*?)"/ism', $attributes, $matches);
4849         if ($matches[1] != "") {
4850                 $author = $matches[1];
4851         }
4852
4853         $profile = "";
4854         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4855         if ($matches[1] != "") {
4856                 $profile = $matches[1];
4857         }
4858
4859         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4860         if ($matches[1] != "") {
4861                 $profile = $matches[1];
4862         }
4863
4864         $avatar = "";
4865         preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4866         if ($matches[1] != "") {
4867                 $avatar = $matches[1];
4868         }
4869
4870         preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4871         if ($matches[1] != "") {
4872                 $avatar = $matches[1];
4873         }
4874
4875         $link = "";
4876         preg_match("/link='(.*?)'/ism", $attributes, $matches);
4877         if ($matches[1] != "") {
4878                 $link = $matches[1];
4879         }
4880
4881         preg_match('/link="(.*?)"/ism', $attributes, $matches);
4882         if ($matches[1] != "") {
4883                 $link = $matches[1];
4884         }
4885
4886         $posted = "";
4887         preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4888         if ($matches[1] != "") {
4889                 $posted = $matches[1];
4890         }
4891
4892         preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4893         if ($matches[1] != "") {
4894                 $posted = $matches[1];
4895         }
4896
4897         $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4898
4899         if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4900                 return false;
4901         }
4902
4903         $reshared_item["body"] = $shared_body;
4904         $reshared_item["author-name"] = $author;
4905         $reshared_item["author-link"] = $profile;
4906         $reshared_item["author-avatar"] = $avatar;
4907         $reshared_item["plink"] = $link;
4908         $reshared_item["created"] = $posted;
4909         $reshared_item["edited"] = $posted;
4910
4911         return $reshared_item;
4912 }
4913
4914 /**
4915  *
4916  * @param string $profile
4917  *
4918  * @return string|false
4919  * @todo remove trailing junk from profile url
4920  * @todo pump.io check has to check the website
4921  */
4922 function api_get_nick($profile)
4923 {
4924         $nick = "";
4925
4926         $r = q(
4927                 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4928                 dbesc(normalise_link($profile))
4929         );
4930
4931         if (DBM::is_result($r)) {
4932                 $nick = $r[0]["nick"];
4933         }
4934
4935         if (!$nick == "") {
4936                 $r = q(
4937                         "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4938                         dbesc(normalise_link($profile))
4939                 );
4940
4941                 if (DBM::is_result($r)) {
4942                         $nick = $r[0]["nick"];
4943                 }
4944         }
4945
4946         if (!$nick == "") {
4947                 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4948                 if ($friendica != $profile) {
4949                         $nick = $friendica;
4950                 }
4951         }
4952
4953         if (!$nick == "") {
4954                 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4955                 if ($diaspora != $profile) {
4956                         $nick = $diaspora;
4957                 }
4958         }
4959
4960         if (!$nick == "") {
4961                 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4962                 if ($twitter != $profile) {
4963                         $nick = $twitter;
4964                 }
4965         }
4966
4967
4968         if (!$nick == "") {
4969                 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4970                 if ($StatusnetHost != $profile) {
4971                         $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4972                         if ($StatusnetUser != $profile) {
4973                                 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4974                                 $user = json_decode($UserData);
4975                                 if ($user) {
4976                                         $nick = $user->screen_name;
4977                                 }
4978                         }
4979                 }
4980         }
4981
4982         // To-Do: look at the page if its really a pumpio site
4983         //if (!$nick == "") {
4984         //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4985         //      if ($pumpio != $profile)
4986         //              $nick = $pumpio;
4987                 //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4988
4989         //}
4990
4991         if ($nick != "") {
4992                 return $nick;
4993         }
4994
4995         return false;
4996 }
4997
4998 /**
4999  *
5000  * @param array $item
5001  *
5002  * @return array
5003  */
5004 function api_in_reply_to($item)
5005 {
5006         $in_reply_to = [];
5007
5008         $in_reply_to['status_id'] = null;
5009         $in_reply_to['user_id'] = null;
5010         $in_reply_to['status_id_str'] = null;
5011         $in_reply_to['user_id_str'] = null;
5012         $in_reply_to['screen_name'] = null;
5013
5014         if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5015                 $r = q(
5016                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5017                         intval($item['uid']),
5018                         dbesc($item['thr-parent'])
5019                 );
5020
5021                 if (DBM::is_result($r)) {
5022                         $in_reply_to['status_id'] = intval($r[0]['id']);
5023                 } else {
5024                         $in_reply_to['status_id'] = intval($item['parent']);
5025                 }
5026
5027                 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5028
5029                 $r = q(
5030                         "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM `item`
5031                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5032                         WHERE `item`.`id` = %d LIMIT 1",
5033                         intval($in_reply_to['status_id'])
5034                 );
5035
5036                 if (DBM::is_result($r)) {
5037                         if ($r[0]['nick'] == "") {
5038                                 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5039                         }
5040
5041                         $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5042                         $in_reply_to['user_id'] = intval($r[0]['id']);
5043                         $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5044                 }
5045
5046                 // There seems to be situation, where both fields are identical:
5047                 // https://github.com/friendica/friendica/issues/1010
5048                 // This is a bugfix for that.
5049                 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5050                         logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5051                         $in_reply_to['status_id'] = null;
5052                         $in_reply_to['user_id'] = null;
5053                         $in_reply_to['status_id_str'] = null;
5054                         $in_reply_to['user_id_str'] = null;
5055                         $in_reply_to['screen_name'] = null;
5056                 }
5057         }
5058
5059         return $in_reply_to;
5060 }
5061
5062 /**
5063  *
5064  * @param string $text
5065  *
5066  * @return string
5067  */
5068 function api_clean_plain_items($text)
5069 {
5070         $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5071
5072         $text = BBCode::cleanPictureLinks($text);
5073         $URLSearchString = "^\[\]";
5074
5075         $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5076
5077         if ($include_entities == "true") {
5078                 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5079         }
5080
5081         // Simplify "attachment" element
5082         $text = api_clean_attachments($text);
5083
5084         return $text;
5085 }
5086
5087 /**
5088  * @brief Removes most sharing information for API text export
5089  *
5090  * @param string $body The original body
5091  *
5092  * @return string Cleaned body
5093  */
5094 function api_clean_attachments($body)
5095 {
5096         $data = BBCode::getAttachmentData($body);
5097
5098         if (empty($data)) {
5099                 return $body;
5100         }
5101         $body = "";
5102
5103         if (isset($data["text"])) {
5104                 $body = $data["text"];
5105         }
5106         if (($body == "") && isset($data["title"])) {
5107                 $body = $data["title"];
5108         }
5109         if (isset($data["url"])) {
5110                 $body .= "\n".$data["url"];
5111         }
5112         $body .= $data["after"];
5113
5114         return $body;
5115 }
5116
5117 /**
5118  *
5119  * @param array $contacts
5120  *
5121  * @return array
5122  */
5123 function api_best_nickname(&$contacts)
5124 {
5125         $best_contact = [];
5126
5127         if (count($contacts) == 0) {
5128                 return;
5129         }
5130
5131         foreach ($contacts as $contact) {
5132                 if ($contact["network"] == "") {
5133                         $contact["network"] = "dfrn";
5134                         $best_contact = [$contact];
5135                 }
5136         }
5137
5138         if (sizeof($best_contact) == 0) {
5139                 foreach ($contacts as $contact) {
5140                         if ($contact["network"] == "dfrn") {
5141                                 $best_contact = [$contact];
5142                         }
5143                 }
5144         }
5145
5146         if (sizeof($best_contact) == 0) {
5147                 foreach ($contacts as $contact) {
5148                         if ($contact["network"] == "dspr") {
5149                                 $best_contact = [$contact];
5150                         }
5151                 }
5152         }
5153
5154         if (sizeof($best_contact) == 0) {
5155                 foreach ($contacts as $contact) {
5156                         if ($contact["network"] == "stat") {
5157                                 $best_contact = [$contact];
5158                         }
5159                 }
5160         }
5161
5162         if (sizeof($best_contact) == 0) {
5163                 foreach ($contacts as $contact) {
5164                         if ($contact["network"] == "pump") {
5165                                 $best_contact = [$contact];
5166                         }
5167                 }
5168         }
5169
5170         if (sizeof($best_contact) == 0) {
5171                 foreach ($contacts as $contact) {
5172                         if ($contact["network"] == "twit") {
5173                                 $best_contact = [$contact];
5174                         }
5175                 }
5176         }
5177
5178         if (sizeof($best_contact) == 1) {
5179                 $contacts = $best_contact;
5180         } else {
5181                 $contacts = [$contacts[0]];
5182         }
5183 }
5184
5185 /**
5186  * Return all or a specified group of the user with the containing contacts.
5187  *
5188  * @param string $type Return type (atom, rss, xml, json)
5189  *
5190  * @return array|string
5191  */
5192 function api_friendica_group_show($type)
5193 {
5194         $a = get_app();
5195
5196         if (api_user() === false) {
5197                 throw new ForbiddenException();
5198         }
5199
5200         // params
5201         $user_info = api_get_user($a);
5202         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5203         $uid = $user_info['uid'];
5204
5205         // get data of the specified group id or all groups if not specified
5206         if ($gid != 0) {
5207                 $r = q(
5208                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5209                         intval($uid),
5210                         intval($gid)
5211                 );
5212                 // error message if specified gid is not in database
5213                 if (!DBM::is_result($r)) {
5214                         throw new BadRequestException("gid not available");
5215                 }
5216         } else {
5217                 $r = q(
5218                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5219                         intval($uid)
5220                 );
5221         }
5222
5223         // loop through all groups and retrieve all members for adding data in the user array
5224         $grps = [];
5225         foreach ($r as $rr) {
5226                 $members = Contact::getByGroupId($rr['id']);
5227                 $users = [];
5228
5229                 if ($type == "xml") {
5230                         $user_element = "users";
5231                         $k = 0;
5232                         foreach ($members as $member) {
5233                                 $user = api_get_user($a, $member['nurl']);
5234                                 $users[$k++.":user"] = $user;
5235                         }
5236                 } else {
5237                         $user_element = "user";
5238                         foreach ($members as $member) {
5239                                 $user = api_get_user($a, $member['nurl']);
5240                                 $users[] = $user;
5241                         }
5242                 }
5243                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5244         }
5245         return api_format_data("groups", $type, ['group' => $grps]);
5246 }
5247 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5248
5249
5250 /**
5251  * Delete the specified group of the user.
5252  *
5253  * @param string $type Return type (atom, rss, xml, json)
5254  *
5255  * @return array|string
5256  */
5257 function api_friendica_group_delete($type)
5258 {
5259         $a = get_app();
5260
5261         if (api_user() === false) {
5262                 throw new ForbiddenException();
5263         }
5264
5265         // params
5266         $user_info = api_get_user($a);
5267         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5268         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5269         $uid = $user_info['uid'];
5270
5271         // error if no gid specified
5272         if ($gid == 0 || $name == "") {
5273                 throw new BadRequestException('gid or name not specified');
5274         }
5275
5276         // get data of the specified group id
5277         $r = q(
5278                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5279                 intval($uid),
5280                 intval($gid)
5281         );
5282         // error message if specified gid is not in database
5283         if (!DBM::is_result($r)) {
5284                 throw new BadRequestException('gid not available');
5285         }
5286
5287         // get data of the specified group id and group name
5288         $rname = q(
5289                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5290                 intval($uid),
5291                 intval($gid),
5292                 dbesc($name)
5293         );
5294         // error message if specified gid is not in database
5295         if (!DBM::is_result($rname)) {
5296                 throw new BadRequestException('wrong group name');
5297         }
5298
5299         // delete group
5300         $ret = Group::removeByName($uid, $name);
5301         if ($ret) {
5302                 // return success
5303                 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5304                 return api_format_data("group_delete", $type, ['result' => $success]);
5305         } else {
5306                 throw new BadRequestException('other API error');
5307         }
5308 }
5309 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5310
5311 /**
5312  * Delete a group.
5313  *
5314  * @param string $type Return type (atom, rss, xml, json)
5315  *
5316  * @return array|string
5317  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5318  */
5319 function api_lists_destroy($type)
5320 {
5321         $a = get_app();
5322
5323         if (api_user() === false) {
5324                 throw new ForbiddenException();
5325         }
5326
5327         // params
5328         $user_info = api_get_user($a);
5329         $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5330         $uid = $user_info['uid'];
5331
5332         // error if no gid specified
5333         if ($gid == 0) {
5334                 throw new BadRequestException('gid not specified');
5335         }
5336
5337         // get data of the specified group id
5338         $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5339         // error message if specified gid is not in database
5340         if (!$group) {
5341                 throw new BadRequestException('gid not available');
5342         }
5343
5344         if (Group::remove($gid)) {
5345                 $list = [
5346                         'name' => $group['name'],
5347                         'id' => intval($gid),
5348                         'id_str' => (string) $gid,
5349                         'user' => $user_info
5350                 ];
5351
5352                 return api_format_data("lists", $type, ['lists' => $list]);
5353         }
5354 }
5355 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5356
5357 /**
5358  * Add a new group to the database.
5359  *
5360  * @param  string $name  Group name
5361  * @param  int    $uid   User ID
5362  * @param  array  $users List of users to add to the group
5363  *
5364  * @return array
5365  */
5366 function group_create($name, $uid, $users = [])
5367 {
5368         // error if no name specified
5369         if ($name == "") {
5370                 throw new BadRequestException('group name not specified');
5371         }
5372
5373         // get data of the specified group name
5374         $rname = q(
5375                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5376                 intval($uid),
5377                 dbesc($name)
5378         );
5379         // error message if specified group name already exists
5380         if (DBM::is_result($rname)) {
5381                 throw new BadRequestException('group name already exists');
5382         }
5383
5384         // check if specified group name is a deleted group
5385         $rname = q(
5386                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5387                 intval($uid),
5388                 dbesc($name)
5389         );
5390         // error message if specified group name already exists
5391         if (DBM::is_result($rname)) {
5392                 $reactivate_group = true;
5393         }
5394
5395         // create group
5396         $ret = Group::create($uid, $name);
5397         if ($ret) {
5398                 $gid = Group::getIdByName($uid, $name);
5399         } else {
5400                 throw new BadRequestException('other API error');
5401         }
5402
5403         // add members
5404         $erroraddinguser = false;
5405         $errorusers = [];
5406         foreach ($users as $user) {
5407                 $cid = $user['cid'];
5408                 // check if user really exists as contact
5409                 $contact = q(
5410                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5411                         intval($cid),
5412                         intval($uid)
5413                 );
5414                 if (count($contact)) {
5415                         Group::addMember($gid, $cid);
5416                 } else {
5417                         $erroraddinguser = true;
5418                         $errorusers[] = $cid;
5419                 }
5420         }
5421
5422         // return success message incl. missing users in array
5423         $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5424
5425         return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5426 }
5427
5428 /**
5429  * Create the specified group with the posted array of contacts.
5430  *
5431  * @param string $type Return type (atom, rss, xml, json)
5432  *
5433  * @return array|string
5434  */
5435 function api_friendica_group_create($type)
5436 {
5437         $a = get_app();
5438
5439         if (api_user() === false) {
5440                 throw new ForbiddenException();
5441         }
5442
5443         // params
5444         $user_info = api_get_user($a);
5445         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5446         $uid = $user_info['uid'];
5447         $json = json_decode($_POST['json'], true);
5448         $users = $json['user'];
5449
5450         $success = group_create($name, $uid, $users);
5451
5452         return api_format_data("group_create", $type, ['result' => $success]);
5453 }
5454 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5455
5456 /**
5457  * Create a new group.
5458  *
5459  * @param string $type Return type (atom, rss, xml, json)
5460  *
5461  * @return array|string
5462  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5463  */
5464 function api_lists_create($type)
5465 {
5466         $a = get_app();
5467
5468         if (api_user() === false) {
5469                 throw new ForbiddenException();
5470         }
5471
5472         // params
5473         $user_info = api_get_user($a);
5474         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5475         $uid = $user_info['uid'];
5476
5477         $success = group_create($name, $uid);
5478         if ($success['success']) {
5479                 $grp = [
5480                         'name' => $success['name'],
5481                         'id' => intval($success['gid']),
5482                         'id_str' => (string) $success['gid'],
5483                         'user' => $user_info
5484                 ];
5485
5486                 return api_format_data("lists", $type, ['lists'=>$grp]);
5487         }
5488 }
5489 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5490
5491 /**
5492  * Update the specified group with the posted array of contacts.
5493  *
5494  * @param string $type Return type (atom, rss, xml, json)
5495  *
5496  * @return array|string
5497  */
5498 function api_friendica_group_update($type)
5499 {
5500         $a = get_app();
5501
5502         if (api_user() === false) {
5503                 throw new ForbiddenException();
5504         }
5505
5506         // params
5507         $user_info = api_get_user($a);
5508         $uid = $user_info['uid'];
5509         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5510         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5511         $json = json_decode($_POST['json'], true);
5512         $users = $json['user'];
5513
5514         // error if no name specified
5515         if ($name == "") {
5516                 throw new BadRequestException('group name not specified');
5517         }
5518
5519         // error if no gid specified
5520         if ($gid == "") {
5521                 throw new BadRequestException('gid not specified');
5522         }
5523
5524         // remove members
5525         $members = Contact::getByGroupId($gid);
5526         foreach ($members as $member) {
5527                 $cid = $member['id'];
5528                 foreach ($users as $user) {
5529                         $found = ($user['cid'] == $cid ? true : false);
5530                 }
5531                 if (!isset($found) || !$found) {
5532                         Group::removeMemberByName($uid, $name, $cid);
5533                 }
5534         }
5535
5536         // add members
5537         $erroraddinguser = false;
5538         $errorusers = [];
5539         foreach ($users as $user) {
5540                 $cid = $user['cid'];
5541                 // check if user really exists as contact
5542                 $contact = q(
5543                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5544                         intval($cid),
5545                         intval($uid)
5546                 );
5547
5548                 if (count($contact)) {
5549                         Group::addMember($gid, $cid);
5550                 } else {
5551                         $erroraddinguser = true;
5552                         $errorusers[] = $cid;
5553                 }
5554         }
5555
5556         // return success message incl. missing users in array
5557         $status = ($erroraddinguser ? "missing user" : "ok");
5558         $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5559         return api_format_data("group_update", $type, ['result' => $success]);
5560 }
5561
5562 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5563
5564 /**
5565  * Update information about a group.
5566  *
5567  * @param string $type Return type (atom, rss, xml, json)
5568  *
5569  * @return array|string
5570  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5571  */
5572 function api_lists_update($type)
5573 {
5574         $a = get_app();
5575
5576         if (api_user() === false) {
5577                 throw new ForbiddenException();
5578         }
5579
5580         // params
5581         $user_info = api_get_user($a);
5582         $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5583         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5584         $uid = $user_info['uid'];
5585
5586         // error if no gid specified
5587         if ($gid == 0) {
5588                 throw new BadRequestException('gid not specified');
5589         }
5590
5591         // get data of the specified group id
5592         $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5593         // error message if specified gid is not in database
5594         if (!$group) {
5595                 throw new BadRequestException('gid not available');
5596         }
5597
5598         if (Group::update($gid, $name)) {
5599                 $list = [
5600                         'name' => $name,
5601                         'id' => intval($gid),
5602                         'id_str' => (string) $gid,
5603                         'user' => $user_info
5604                 ];
5605
5606                 return api_format_data("lists", $type, ['lists' => $list]);
5607         }
5608 }
5609
5610 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5611
5612 /**
5613  *
5614  * @param string $type Return type (atom, rss, xml, json)
5615  *
5616  * @return array|string
5617  */
5618 function api_friendica_activity($type)
5619 {
5620         $a = get_app();
5621
5622         if (api_user() === false) {
5623                 throw new ForbiddenException();
5624         }
5625         $verb = strtolower($a->argv[3]);
5626         $verb = preg_replace("|\..*$|", "", $verb);
5627
5628         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5629
5630         $res = Item::performLike($id, $verb);
5631
5632         if ($res) {
5633                 if ($type == "xml") {
5634                         $ok = "true";
5635                 } else {
5636                         $ok = "ok";
5637                 }
5638                 return api_format_data('ok', $type, ['ok' => $ok]);
5639         } else {
5640                 throw new BadRequestException('Error adding activity');
5641         }
5642 }
5643
5644 /// @TODO move to top of file or somewhere better
5645 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5646 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5647 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5648 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5649 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5650 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5651 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5652 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5653 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5654 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5655
5656 /**
5657  * @brief Returns notifications
5658  *
5659  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5660  * @return string|array
5661 */
5662 function api_friendica_notification($type)
5663 {
5664         $a = get_app();
5665
5666         if (api_user() === false) {
5667                 throw new ForbiddenException();
5668         }
5669         if ($a->argc!==3) {
5670                 throw new BadRequestException("Invalid argument count");
5671         }
5672         $nm = new NotificationsManager();
5673
5674         $notes = $nm->getAll([], "+seen -date", 50);
5675
5676         if ($type == "xml") {
5677                 $xmlnotes = [];
5678                 foreach ($notes as $note) {
5679                         $xmlnotes[] = ["@attributes" => $note];
5680                 }
5681
5682                 $notes = $xmlnotes;
5683         }
5684
5685         return api_format_data("notes", $type, ['note' => $notes]);
5686 }
5687
5688 /**
5689  * POST request with 'id' param as notification id
5690  *
5691  * @brief Set notification as seen and returns associated item (if possible)
5692  *
5693  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5694  * @return string|array
5695  */
5696 function api_friendica_notification_seen($type)
5697 {
5698         $a = get_app();
5699         $user_info = api_get_user($a);
5700
5701         if (api_user() === false || $user_info === false) {
5702                 throw new ForbiddenException();
5703         }
5704         if ($a->argc!==4) {
5705                 throw new BadRequestException("Invalid argument count");
5706         }
5707
5708         $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5709
5710         $nm = new NotificationsManager();
5711         $note = $nm->getByID($id);
5712         if (is_null($note)) {
5713                 throw new BadRequestException("Invalid argument");
5714         }
5715
5716         $nm->setSeen($note);
5717         if ($note['otype']=='item') {
5718                 // would be really better with an ItemsManager and $im->getByID() :-P
5719                 $item = Item::selectFirst(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5720                 if (DBM::is_result($$item)) {
5721                         // we found the item, return it to the user
5722                         $ret = api_format_items([$item], $user_info, false, $type);
5723                         $data = ['status' => $ret];
5724                         return api_format_data("status", $type, $data);
5725                 }
5726                 // the item can't be found, but we set the note as seen, so we count this as a success
5727         }
5728         return api_format_data('result', $type, ['result' => "success"]);
5729 }
5730
5731 /// @TODO move to top of file or somewhere better
5732 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5733 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5734
5735 /**
5736  * @brief update a direct_message to seen state
5737  *
5738  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5739  * @return string|array (success result=ok, error result=error with error message)
5740  */
5741 function api_friendica_direct_messages_setseen($type)
5742 {
5743         $a = get_app();
5744         if (api_user() === false) {
5745                 throw new ForbiddenException();
5746         }
5747
5748         // params
5749         $user_info = api_get_user($a);
5750         $uid = $user_info['uid'];
5751         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5752
5753         // return error if id is zero
5754         if ($id == "") {
5755                 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5756                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5757         }
5758
5759         // error message if specified id is not in database
5760         if (!dba::exists('mail', ['id' => $id, 'uid' => $uid])) {
5761                 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5762                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5763         }
5764
5765         // update seen indicator
5766         $result = dba::update('mail', ['seen' => true], ['id' => $id]);
5767
5768         if ($result) {
5769                 // return success
5770                 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5771                 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5772         } else {
5773                 $answer = ['result' => 'error', 'message' => 'unknown error'];
5774                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5775         }
5776 }
5777
5778 /// @TODO move to top of file or somewhere better
5779 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5780
5781 /**
5782  * @brief search for direct_messages containing a searchstring through api
5783  *
5784  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5785  * @param string $box
5786  * @return string|array (success: success=true if found and search_result contains found messages,
5787  *                          success=false if nothing was found, search_result='nothing found',
5788  *                 error: result=error with error message)
5789  */
5790 function api_friendica_direct_messages_search($type, $box = "")
5791 {
5792         $a = get_app();
5793
5794         if (api_user() === false) {
5795                 throw new ForbiddenException();
5796         }
5797
5798         // params
5799         $user_info = api_get_user($a);
5800         $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5801         $uid = $user_info['uid'];
5802
5803         // error if no searchstring specified
5804         if ($searchstring == "") {
5805                 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5806                 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5807         }
5808
5809         // get data for the specified searchstring
5810         $r = q(
5811                 "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",
5812                 intval($uid),
5813                 dbesc('%'.$searchstring.'%')
5814         );
5815
5816         $profile_url = $user_info["url"];
5817
5818         // message if nothing was found
5819         if (!DBM::is_result($r)) {
5820                 $success = ['success' => false, 'search_results' => 'problem with query'];
5821         } elseif (count($r) == 0) {
5822                 $success = ['success' => false, 'search_results' => 'nothing found'];
5823         } else {
5824                 $ret = [];
5825                 foreach ($r as $item) {
5826                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
5827                                 $recipient = $user_info;
5828                                 $sender = api_get_user($a, normalise_link($item['contact-url']));
5829                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5830                                 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5831                                 $sender = $user_info;
5832                         }
5833
5834                         if (isset($recipient) && isset($sender)) {
5835                                 $ret[] = api_format_messages($item, $recipient, $sender);
5836                         }
5837                 }
5838                 $success = ['success' => true, 'search_results' => $ret];
5839         }
5840
5841         return api_format_data("direct_message_search", $type, ['$result' => $success]);
5842 }
5843
5844 /// @TODO move to top of file or somewhere better
5845 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5846
5847 /**
5848  * @brief return data of all the profiles a user has to the client
5849  *
5850  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5851  * @return string|array
5852  */
5853 function api_friendica_profile_show($type)
5854 {
5855         $a = get_app();
5856
5857         if (api_user() === false) {
5858                 throw new ForbiddenException();
5859         }
5860
5861         // input params
5862         $profile_id = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5863
5864         // retrieve general information about profiles for user
5865         $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5866         $directory = Config::get('system', 'directory');
5867
5868         // get data of the specified profile id or all profiles of the user if not specified
5869         if ($profile_id != 0) {
5870                 $r = q(
5871                         "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5872                         intval(api_user()),
5873                         intval($profile_id)
5874                 );
5875
5876                 // error message if specified gid is not in database
5877                 if (!DBM::is_result($r)) {
5878                         throw new BadRequestException("profile_id not available");
5879                 }
5880         } else {
5881                 $r = q(
5882                         "SELECT * FROM `profile` WHERE `uid` = %d",
5883                         intval(api_user())
5884                 );
5885         }
5886         // loop through all returned profiles and retrieve data and users
5887         $k = 0;
5888         $profiles = [];
5889         foreach ($r as $rr) {
5890                 $profile = api_format_items_profiles($rr);
5891
5892                 // select all users from contact table, loop and prepare standard return for user data
5893                 $users = [];
5894                 $nurls = q(
5895                         "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5896                         intval(api_user()),
5897                         intval($rr['profile_id'])
5898                 );
5899
5900                 foreach ($nurls as $nurl) {
5901                         $user = api_get_user($a, $nurl['nurl']);
5902                         ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5903                 }
5904                 $profile['users'] = $users;
5905
5906                 // add prepared profile data to array for final return
5907                 if ($type == "xml") {
5908                         $profiles[$k++ . ":profile"] = $profile;
5909                 } else {
5910                         $profiles[] = $profile;
5911                 }
5912         }
5913
5914         // return settings, authenticated user and profiles data
5915         $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5916
5917         $result = ['multi_profiles' => $multi_profiles ? true : false,
5918                                         'global_dir' => $directory,
5919                                         'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5920                                         'profiles' => $profiles];
5921         return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5922 }
5923 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5924
5925 /**
5926  * Returns a list of saved searches.
5927  *
5928  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5929  *
5930  * @param  string $type Return format: json or xml
5931  *
5932  * @return string|array
5933  */
5934 function api_saved_searches_list($type)
5935 {
5936         $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5937
5938         $result = [];
5939         while ($term = $terms->fetch()) {
5940                 $result[] = [
5941                         'created_at' => api_date(time()),
5942                         'id' => intval($term['id']),
5943                         'id_str' => $term['id'],
5944                         'name' => $term['term'],
5945                         'position' => null,
5946                         'query' => $term['term']
5947                 ];
5948         }
5949
5950         dba::close($terms);
5951
5952         return api_format_data("terms", $type, ['terms' => $result]);
5953 }
5954
5955 /// @TODO move to top of file or somewhere better
5956 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5957
5958 /*
5959 @TODO Maybe open to implement?
5960 To.Do:
5961         [pagename] => api/1.1/statuses/lookup.json
5962         [id] => 605138389168451584
5963         [include_cards] => true
5964         [cards_platform] => Android-12
5965         [include_entities] => true
5966         [include_my_retweet] => 1
5967         [include_rts] => 1
5968         [include_reply_count] => true
5969         [include_descendent_reply_count] => true
5970 (?)
5971
5972
5973 Not implemented by now:
5974 statuses/retweets_of_me
5975 friendships/create
5976 friendships/destroy
5977 friendships/exists
5978 friendships/show
5979 account/update_location
5980 account/update_profile_background_image
5981 blocks/create
5982 blocks/destroy
5983 friendica/profile/update
5984 friendica/profile/create
5985 friendica/profile/delete
5986
5987 Not implemented in status.net:
5988 statuses/retweeted_to_me
5989 statuses/retweeted_by_me
5990 direct_messages/destroy
5991 account/end_session
5992 account/update_delivery_device
5993 notifications/follow
5994 notifications/leave
5995 blocks/exists
5996 blocks/blocking
5997 lists
5998 */