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