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