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