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