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