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