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