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