3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
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\ForbiddenException;
35 use Friendica\Network\HTTPException\InternalServerErrorException;
36 use Friendica\Network\HTTPException\MethodNotAllowedException;
37 use Friendica\Network\HTTPException\NotFoundException;
38 use Friendica\Network\HTTPException\NotImplementedException;
39 use Friendica\Network\HTTPException\TooManyRequestsException;
40 use Friendica\Network\HTTPException\UnauthorizedException;
41 use Friendica\Object\Image;
42 use Friendica\Protocol\Diaspora;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Network;
45 use Friendica\Util\Proxy as ProxyUtils;
46 use Friendica\Util\Strings;
47 use Friendica\Util\XML;
49 require_once 'mod/share.php';
50 require_once 'mod/item.php';
51 require_once 'mod/wall_upload.php';
53 define('API_METHOD_ANY', '*');
54 define('API_METHOD_GET', 'GET');
55 define('API_METHOD_POST', 'POST,PUT');
56 define('API_METHOD_DELETE', 'POST,DELETE');
58 define('API_LOG_PREFIX', 'API {action} - ');
64 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
65 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
66 * into a page, and visitors will post something without noticing it).
68 * @brief Auth API user
72 if (!empty($_SESSION['allow_api'])) {
80 * Clients can send 'source' parameter to be show in post metadata
81 * as "sent via <source>".
82 * Some clients doesn't send a source param, we support ones we know
85 * @brief Get source name from API client
88 * Client source name, default to "api" if unset/unknown
92 if (requestdata('source')) {
93 return requestdata('source');
96 // Support for known clients that doesn't send a source name
97 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
98 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
102 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
104 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
111 * @brief Format date for API
113 * @param string $str Source date, as UTC
114 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
116 function api_date($str)
118 // Wed May 23 06:01:13 +0000 2007
119 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
123 * Register a function to be the endpoint for defined API path.
125 * @brief Register API endpoint
127 * @param string $path API URL path, relative to System::baseUrl()
128 * @param string $func Function name to call on path request
129 * @param bool $auth API need logged user
130 * @param string $method HTTP method reqiured to call this endpoint.
131 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
132 * Default to API_METHOD_ANY
134 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
144 // Workaround for hotot
145 $path = str_replace("api/", "api/1.1/", $path);
155 * Log in user via OAuth1 or Simple HTTP Auth.
156 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
158 * @brief Login API user
160 * @param object $a App
161 * @hook 'authenticate'
163 * 'username' => username from login form
164 * 'password' => password from login form
165 * 'authenticated' => return status,
166 * 'user_record' => return authenticated user record
168 * array $user logged user record
170 function api_login(App $a)
172 $oauth1 = new FKOAuth1();
175 $request = OAuthRequest::from_request();
176 list($consumer, $token) = $oauth1->verify_request($request);
177 if (!is_null($token)) {
178 $oauth1->loginUser($token->uid);
179 Hook::callAll('logged_in', $a->user);
182 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
183 var_dump($consumer, $token);
185 } catch (Exception $e) {
186 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
189 // workaround for HTTP-auth in CGI mode
190 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
191 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
192 if (strlen($userpass)) {
193 list($name, $password) = explode(':', $userpass);
194 $_SERVER['PHP_AUTH_USER'] = $name;
195 $_SERVER['PHP_AUTH_PW'] = $password;
199 if (empty($_SERVER['PHP_AUTH_USER'])) {
200 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
201 header('WWW-Authenticate: Basic realm="Friendica"');
202 throw new UnauthorizedException("This API requires login");
205 $user = defaults($_SERVER, 'PHP_AUTH_USER', '');
206 $password = defaults($_SERVER, 'PHP_AUTH_PW', '');
208 // allow "user@server" login (but ignore 'server' part)
209 $at = strstr($user, "@", true);
214 // next code from mod/auth.php. needs better solution
218 'username' => trim($user),
219 'password' => trim($password),
220 'authenticated' => 0,
221 'user_record' => null,
225 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
226 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
227 * and later addons should not interfere with an earlier one that succeeded.
229 Hook::callAll('authenticate', $addon_auth);
231 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
232 $record = $addon_auth['user_record'];
234 $user_id = User::authenticate(trim($user), trim($password));
235 if ($user_id !== false) {
236 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
240 if (!DBA::isResult($record)) {
241 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
242 header('WWW-Authenticate: Basic realm="Friendica"');
243 //header('HTTP/1.0 401 Unauthorized');
244 //die('This api requires login');
245 throw new UnauthorizedException("This API requires login");
248 Authentication::setAuthenticatedSessionForUser($record);
250 $_SESSION["allow_api"] = true;
252 Hook::callAll('logged_in', $a->user);
256 * API endpoints can define which HTTP method to accept when called.
257 * This function check the current HTTP method agains endpoint
260 * @brief Check HTTP method of called API
262 * @param string $method Required methods, uppercase, separated by comma
265 function api_check_method($method)
267 if ($method == "*") {
270 return (stripos($method, defaults($_SERVER, 'REQUEST_METHOD', 'GET')) !== false);
274 * Authenticate user, call registered API function, set HTTP headers
276 * @brief Main API entry point
278 * @param object $a App
279 * @return string|array API call result
281 function api_call(App $a)
283 global $API, $called_api;
286 if (strpos($a->query_string, ".xml") > 0) {
289 if (strpos($a->query_string, ".json") > 0) {
292 if (strpos($a->query_string, ".rss") > 0) {
295 if (strpos($a->query_string, ".atom") > 0) {
300 foreach ($API as $p => $info) {
301 if (strpos($a->query_string, $p) === 0) {
302 if (!api_check_method($info['method'])) {
303 throw new MethodNotAllowedException();
306 $called_api = explode("/", $p);
307 //unset($_SERVER['PHP_AUTH_USER']);
309 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
310 if (!empty($info['auth']) && api_user() === false) {
314 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
315 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
317 $stamp = microtime(true);
318 $return = call_user_func($info['func'], $type);
319 $duration = (float) (microtime(true) - $stamp);
321 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
323 if (Config::get("system", "profiler")) {
324 $duration = microtime(true)-$a->performance["start"];
326 /// @TODO round() really everywhere?
328 'API {action} performance',
332 'database_read' => round($a->performance["database"] - $a->performance["database_write"], 3),
333 'database_write' => round($a->performance["database_write"], 3),
334 'cache_read' => round($a->performance["cache"], 3),
335 'cache_write' => round($a->performance["cache_write"], 3),
336 'network_io' => round($a->performance["network"], 2),
337 'file_io' => round($a->performance["file"], 2),
338 'other_io' => round($duration - ($a->performance["database"]
339 + $a->performance["cache"] + $a->performance["cache_write"]
340 + $a->performance["network"] + $a->performance["file"]), 2),
341 'total' => round($duration, 2)
345 if (Config::get("rendertime", "callstack")) {
346 $o = "Database Read:\n";
347 foreach ($a->callstack["database"] as $func => $time) {
348 $time = round($time, 3);
350 $o .= $func . ": " . $time . "\n";
353 $o .= "\nDatabase Write:\n";
354 foreach ($a->callstack["database_write"] as $func => $time) {
355 $time = round($time, 3);
357 $o .= $func . ": " . $time . "\n";
361 $o = "Cache Read:\n";
362 foreach ($a->callstack["cache"] as $func => $time) {
363 $time = round($time, 3);
365 $o .= $func . ": " . $time . "\n";
368 $o .= "\nCache Write:\n";
369 foreach ($a->callstack["cache_write"] as $func => $time) {
370 $time = round($time, 3);
372 $o .= $func . ": " . $time . "\n";
376 $o .= "\nNetwork:\n";
377 foreach ($a->callstack["network"] as $func => $time) {
378 $time = round($time, 3);
380 $o .= $func . ": " . $time . "\n";
383 Logger::debug($o, ['module' => 'api', 'action' => 'call']);
387 if (false === $return) {
389 * api function returned false withour throw an
390 * exception. This should not happend, throw a 500
392 throw new InternalServerErrorException();
397 header("Content-Type: text/xml");
400 header("Content-Type: application/json");
401 $json = json_encode(end($return));
402 if (!empty($_GET['callback'])) {
403 $json = $_GET['callback'] . "(" . $json . ")";
408 header("Content-Type: application/rss+xml");
409 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
412 header("Content-Type: application/atom+xml");
413 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
420 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call']);
421 throw new NotImplementedException();
422 } catch (HTTPException $e) {
423 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
424 return api_error($type, $e);
429 * @brief Format API error string
431 * @param string $type Return type (xml, json, rss, as)
432 * @param object $e HTTPException Error object
433 * @return string|array error message formatted as $type
435 function api_error($type, $e)
439 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
440 /// @TODO: https://dev.twitter.com/overview/api/response-codes
442 $error = ["error" => $error,
443 "code" => $e->httpcode . " " . $e->httpdesc,
444 "request" => $a->query_string];
446 $return = api_format_data('status', $type, ['status' => $error]);
450 header("Content-Type: text/xml");
453 header("Content-Type: application/json");
454 $return = json_encode($return);
457 header("Content-Type: application/rss+xml");
460 header("Content-Type: application/atom+xml");
468 * @brief Set values for RSS template
471 * @param array $arr Array to be passed to template
472 * @param array $user_info User info
474 * @todo find proper type-hints
476 function api_rss_extra(App $a, $arr, $user_info)
478 if (is_null($user_info)) {
479 $user_info = api_get_user($a);
482 $arr['$user'] = $user_info;
484 'alternate' => $user_info['url'],
485 'self' => System::baseUrl() . "/" . $a->query_string,
486 'base' => System::baseUrl(),
487 'updated' => api_date(null),
488 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
489 'language' => $user_info['lang'],
490 'logo' => System::baseUrl() . "/images/friendica-32.png",
498 * @brief Unique contact to contact url.
500 * @param int $id Contact id
501 * @return bool|string
502 * Contact url or False if contact id is unknown
504 function api_unique_id_to_nurl($id)
506 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
508 if (DBA::isResult($r)) {
516 * @brief Get user info array.
518 * @param object $a App
519 * @param int|string $contact_id Contact ID or URL
521 function api_get_user(App $a, $contact_id = null)
529 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
531 // Searching for contact URL
532 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
533 $user = DBA::escape(Strings::normaliseLink($contact_id));
535 $extra_query = "AND `contact`.`nurl` = '%s' ";
536 if (api_user() !== false) {
537 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
541 // Searching for contact id with uid = 0
542 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
543 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
546 throw new BadRequestException("User ID ".$contact_id." not found.");
550 $extra_query = "AND `contact`.`nurl` = '%s' ";
551 if (api_user() !== false) {
552 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
556 if (is_null($user) && !empty($_GET['user_id'])) {
557 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
560 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
564 $extra_query = "AND `contact`.`nurl` = '%s' ";
565 if (api_user() !== false) {
566 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
569 if (is_null($user) && !empty($_GET['screen_name'])) {
570 $user = DBA::escape($_GET['screen_name']);
571 $extra_query = "AND `contact`.`nick` = '%s' ";
572 if (api_user() !== false) {
573 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
577 if (is_null($user) && !empty($_GET['profileurl'])) {
578 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
579 $extra_query = "AND `contact`.`nurl` = '%s' ";
580 if (api_user() !== false) {
581 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
585 // $called_api is the API path exploded on / and is expected to have at least 2 elements
586 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
587 $argid = count($called_api);
588 if (!empty($a->argv[$argid])) {
589 $data = explode(".", $a->argv[$argid]);
590 if (count($data) > 1) {
591 list($user, $null) = $data;
594 if (is_numeric($user)) {
595 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
599 $extra_query = "AND `contact`.`nurl` = '%s' ";
600 if (api_user() !== false) {
601 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
605 $user = DBA::escape($user);
606 $extra_query = "AND `contact`.`nick` = '%s' ";
607 if (api_user() !== false) {
608 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
613 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
616 if (api_user() === false) {
620 $user = $_SESSION['uid'];
621 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
625 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
629 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
635 // Selecting the id by priority, friendica first
636 if (is_array($uinfo)) {
637 api_best_nickname($uinfo);
640 // if the contact wasn't found, fetch it from the contacts with uid = 0
641 if (!DBA::isResult($uinfo)) {
643 throw new BadRequestException("User not found.");
646 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
648 if (DBA::isResult($contact)) {
649 // If no nick where given, extract it from the address
650 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
651 $contact['nick'] = api_get_nick($contact["url"]);
655 'id' => $contact["id"],
656 'id_str' => (string) $contact["id"],
657 'name' => $contact["name"],
658 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
659 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
660 'description' => $contact["about"],
661 'profile_image_url' => $contact["micro"],
662 'profile_image_url_https' => $contact["micro"],
663 'profile_image_url_profile_size' => $contact["thumb"],
664 'profile_image_url_large' => $contact["photo"],
665 'url' => $contact["url"],
666 'protected' => false,
667 'followers_count' => 0,
668 'friends_count' => 0,
670 'created_at' => api_date($contact["created"]),
671 'favourites_count' => 0,
673 'time_zone' => 'UTC',
674 'geo_enabled' => false,
676 'statuses_count' => 0,
678 'contributors_enabled' => false,
679 'is_translator' => false,
680 'is_translation_enabled' => false,
681 'following' => false,
682 'follow_request_sent' => false,
683 'statusnet_blocking' => false,
684 'notifications' => false,
685 'statusnet_profile_url' => $contact["url"],
687 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
688 'pid' => Contact::getIdForURL($contact["url"], 0, true),
690 'network' => $contact["network"],
695 throw new BadRequestException("User ".$url." not found.");
699 if ($uinfo[0]['self']) {
700 if ($uinfo[0]['network'] == "") {
701 $uinfo[0]['network'] = Protocol::DFRN;
704 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
705 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
712 // Add a nick if it isn't present there
713 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
714 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
717 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
719 if (!empty($profile['about'])) {
720 $description = $profile['about'];
722 $description = $uinfo[0]["about"];
725 if (!empty($usr['default-location'])) {
726 $location = $usr['default-location'];
727 } elseif (!empty($uinfo[0]["location"])) {
728 $location = $uinfo[0]["location"];
730 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
734 'id' => intval($pcontact_id),
735 'id_str' => (string) intval($pcontact_id),
736 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
737 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
738 'location' => $location,
739 'description' => $description,
740 'profile_image_url' => $uinfo[0]['micro'],
741 'profile_image_url_https' => $uinfo[0]['micro'],
742 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
743 'profile_image_url_large' => $uinfo[0]["photo"],
744 'url' => $uinfo[0]['url'],
745 'protected' => false,
746 'followers_count' => intval($countfollowers),
747 'friends_count' => intval($countfriends),
749 'created_at' => api_date($uinfo[0]['created']),
750 'favourites_count' => intval($starred),
752 'time_zone' => 'UTC',
753 'geo_enabled' => false,
755 'statuses_count' => intval($countitems),
757 'contributors_enabled' => false,
758 'is_translator' => false,
759 'is_translation_enabled' => false,
760 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
761 'follow_request_sent' => false,
762 'statusnet_blocking' => false,
763 'notifications' => false,
765 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
766 'statusnet_profile_url' => $uinfo[0]['url'],
767 'uid' => intval($uinfo[0]['uid']),
768 'cid' => intval($uinfo[0]['cid']),
769 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
770 'self' => $uinfo[0]['self'],
771 'network' => $uinfo[0]['network'],
774 // If this is a local user and it uses Frio, we can get its color preferences.
776 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
777 if ($theme_info['theme'] === 'frio') {
778 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
780 if ($schema && ($schema != '---')) {
781 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
782 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
783 require_once $schemefile;
786 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
787 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
788 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
790 if (empty($nav_bg)) {
793 if (empty($link_color)) {
794 $link_color = "#6fdbe8";
796 if (empty($bgcolor)) {
797 $bgcolor = "#ededed";
800 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
801 $ret['profile_link_color'] = str_replace('#', '', $link_color);
802 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
810 * @brief return api-formatted array for item's author and owner
812 * @param object $a App
813 * @param array $item item from db
814 * @return array(array:author, array:owner)
816 function api_item_get_user(App $a, $item)
818 $status_user = api_get_user($a, defaults($item, 'author-id', null));
820 $status_user["protected"] = defaults($item, 'private', 0);
822 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
823 $owner_user = api_get_user($a, defaults($item, 'owner-id', null));
825 $owner_user = $status_user;
828 return ([$status_user, $owner_user]);
832 * @brief walks recursively through an array with the possibility to change value and key
834 * @param array $array The array to walk through
835 * @param string $callback The callback function
837 * @return array the transformed array
839 function api_walk_recursive(array &$array, callable $callback)
843 foreach ($array as $k => $v) {
845 if ($callback($v, $k)) {
846 $new_array[$k] = api_walk_recursive($v, $callback);
849 if ($callback($v, $k)) {
860 * @brief Callback function to transform the array in an array that can be transformed in a XML file
862 * @param mixed $item Array item value
863 * @param string $key Array key
865 * @return boolean Should the array item be deleted?
867 function api_reformat_xml(&$item, &$key)
869 if (is_bool($item)) {
870 $item = ($item ? "true" : "false");
873 if (substr($key, 0, 10) == "statusnet_") {
874 $key = "statusnet:".substr($key, 10);
875 } elseif (substr($key, 0, 10) == "friendica_") {
876 $key = "friendica:".substr($key, 10);
878 /// @TODO old-lost code?
880 // $key = "default:".$key;
886 * @brief Creates the XML from a JSON style array
888 * @param array $data JSON style array
889 * @param string $root_element Name of the root element
891 * @return string The XML data
893 function api_create_xml(array $data, $root_element)
895 $childname = key($data);
896 $data2 = array_pop($data);
898 $namespaces = ["" => "http://api.twitter.com",
899 "statusnet" => "http://status.net/schema/api/1/",
900 "friendica" => "http://friendi.ca/schema/api/1/",
901 "georss" => "http://www.georss.org/georss"];
903 /// @todo Auto detection of needed namespaces
904 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
908 if (is_array($data2)) {
910 api_walk_recursive($data2, "api_reformat_xml");
916 foreach ($data2 as $item) {
917 $data4[$i++ . ":" . $childname] = $item;
924 $data3 = [$root_element => $data2];
926 $ret = XML::fromArray($data3, $xml, false, $namespaces);
931 * @brief Formats the data according to the data type
933 * @param string $root_element Name of the root element
934 * @param string $type Return type (atom, rss, xml, json)
935 * @param array $data JSON style array
937 * @return (string|array) XML data or JSON data
939 function api_format_data($root_element, $type, $data)
945 $ret = api_create_xml($data, $root_element);
960 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
961 * returns a 401 status code and an error message if not.
962 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
964 * @param string $type Return type (atom, rss, xml, json)
966 function api_account_verify_credentials($type)
971 if (api_user() === false) {
972 throw new ForbiddenException();
975 unset($_REQUEST["user_id"]);
976 unset($_GET["user_id"]);
978 unset($_REQUEST["screen_name"]);
979 unset($_GET["screen_name"]);
981 $skip_status = defaults($_REQUEST, 'skip_status', false);
983 $user_info = api_get_user($a);
985 // "verified" isn't used here in the standard
986 unset($user_info["verified"]);
988 // - Adding last status
990 $user_info["status"] = api_status_show("raw");
991 if (!count($user_info["status"])) {
992 unset($user_info["status"]);
994 unset($user_info["status"]["user"]);
998 // "uid" and "self" are only needed for some internal stuff, so remove it from here
999 unset($user_info["uid"]);
1000 unset($user_info["self"]);
1002 return api_format_data("user", $type, ['user' => $user_info]);
1005 /// @TODO move to top of file or somewhere better
1006 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1009 * Get data from $_POST or $_GET
1013 function requestdata($k)
1015 if (!empty($_POST[$k])) {
1018 if (!empty($_GET[$k])) {
1025 * Deprecated function to upload media.
1027 * @param string $type Return type (atom, rss, xml, json)
1029 * @return array|string
1031 function api_statuses_mediap($type)
1035 if (api_user() === false) {
1036 Logger::log('api_statuses_update: no user');
1037 throw new ForbiddenException();
1039 $user_info = api_get_user($a);
1041 $_REQUEST['profile_uid'] = api_user();
1042 $_REQUEST['api_source'] = true;
1043 $txt = requestdata('status');
1044 /// @TODO old-lost code?
1045 //$txt = urldecode(requestdata('status'));
1047 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1048 $txt = HTML::toBBCodeVideo($txt);
1049 $config = HTMLPurifier_Config::createDefault();
1050 $config->set('Cache.DefinitionImpl', null);
1051 $purifier = new HTMLPurifier($config);
1052 $txt = $purifier->purify($txt);
1054 $txt = HTML::toBBCode($txt);
1056 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1058 $picture = wall_upload_post($a, false);
1060 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1061 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1062 $item_id = item_post($a);
1064 // output the post that we just posted.
1065 return api_status_show($type, $item_id);
1068 /// @TODO move this to top of file or somewhere better!
1069 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1072 * Updates the user’s current status.
1074 * @param string $type Return type (atom, rss, xml, json)
1076 * @return array|string
1077 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1079 function api_statuses_update($type)
1083 if (api_user() === false) {
1084 Logger::log('api_statuses_update: no user');
1085 throw new ForbiddenException();
1090 // convert $_POST array items to the form we use for web posts.
1091 if (requestdata('htmlstatus')) {
1092 $txt = requestdata('htmlstatus');
1093 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1094 $txt = HTML::toBBCodeVideo($txt);
1096 $config = HTMLPurifier_Config::createDefault();
1097 $config->set('Cache.DefinitionImpl', null);
1099 $purifier = new HTMLPurifier($config);
1100 $txt = $purifier->purify($txt);
1102 $_REQUEST['body'] = HTML::toBBCode($txt);
1105 $_REQUEST['body'] = requestdata('status');
1108 $_REQUEST['title'] = requestdata('title');
1110 $parent = requestdata('in_reply_to_status_id');
1112 // Twidere sends "-1" if it is no reply ...
1113 if ($parent == -1) {
1117 if (ctype_digit($parent)) {
1118 $_REQUEST['parent'] = $parent;
1120 $_REQUEST['parent_uri'] = $parent;
1123 if (requestdata('lat') && requestdata('long')) {
1124 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1126 $_REQUEST['profile_uid'] = api_user();
1129 // Check for throttling (maximum posts per day, week and month)
1130 $throttle_day = Config::get('system', 'throttle_limit_day');
1131 if ($throttle_day > 0) {
1132 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1134 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1135 $posts_day = DBA::count('thread', $condition);
1137 if ($posts_day > $throttle_day) {
1138 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1139 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1140 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));
1144 $throttle_week = Config::get('system', 'throttle_limit_week');
1145 if ($throttle_week > 0) {
1146 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1148 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1149 $posts_week = DBA::count('thread', $condition);
1151 if ($posts_week > $throttle_week) {
1152 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1153 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1154 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));
1158 $throttle_month = Config::get('system', 'throttle_limit_month');
1159 if ($throttle_month > 0) {
1160 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1162 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1163 $posts_month = DBA::count('thread', $condition);
1165 if ($posts_month > $throttle_month) {
1166 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1167 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1168 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));
1173 if (!empty($_FILES['media'])) {
1174 // upload the image if we have one
1175 $picture = wall_upload_post($a, false);
1176 if (is_array($picture)) {
1177 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1181 // To-Do: Multiple IDs
1182 if (requestdata('media_ids')) {
1184 "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",
1185 intval(requestdata('media_ids')),
1188 if (DBA::isResult($r)) {
1189 $phototypes = Image::supportedTypes();
1190 $ext = $phototypes[$r[0]['type']];
1191 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1192 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1196 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1198 $_REQUEST['api_source'] = true;
1200 if (empty($_REQUEST['source'])) {
1201 $_REQUEST["source"] = api_source();
1204 // call out normal post function
1205 $item_id = item_post($a);
1207 // output the post that we just posted.
1208 return api_status_show($type, $item_id);
1211 /// @TODO move to top of file or somewhere better
1212 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1213 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1216 * Uploads an image to Friendica.
1219 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1221 function api_media_upload()
1225 if (api_user() === false) {
1226 Logger::log('no user');
1227 throw new ForbiddenException();
1232 if (empty($_FILES['media'])) {
1234 throw new BadRequestException("No media.");
1237 $media = wall_upload_post($a, false);
1240 throw new InternalServerErrorException();
1244 $returndata["media_id"] = $media["id"];
1245 $returndata["media_id_string"] = (string)$media["id"];
1246 $returndata["size"] = $media["size"];
1247 $returndata["image"] = ["w" => $media["width"],
1248 "h" => $media["height"],
1249 "image_type" => $media["type"],
1250 "friendica_preview_url" => $media["preview"]];
1252 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1254 return ["media" => $returndata];
1257 /// @TODO move to top of file or somewhere better
1258 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1262 * @param string $type Return type (atom, rss, xml, json)
1264 * @return array|string
1266 function api_status_show($type, $item_id = 0)
1270 $user_info = api_get_user($a);
1272 Logger::log('api_status_show: user_info: '.print_r($user_info, true), Logger::DEBUG);
1274 if ($type == "raw") {
1275 $privacy_sql = "AND NOT `private`";
1280 if (!empty($item_id)) {
1281 // Get the item with the given id
1282 $condition = ['id' => $item_id];
1284 // get last public wall message
1285 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1286 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1288 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1290 if (DBA::isResult($lastwall)) {
1291 $in_reply_to = api_in_reply_to($lastwall);
1293 $converted = api_convert_item($lastwall);
1295 if ($type == "xml") {
1296 $geo = "georss:point";
1302 'created_at' => api_date($lastwall['created']),
1303 'id' => intval($lastwall['id']),
1304 'id_str' => (string) $lastwall['id'],
1305 'text' => $converted["text"],
1306 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1307 'truncated' => false,
1308 'in_reply_to_status_id' => $in_reply_to['status_id'],
1309 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1310 'in_reply_to_user_id' => $in_reply_to['user_id'],
1311 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1312 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1313 'user' => $user_info,
1315 'coordinates' => '',
1317 'contributors' => '',
1318 'is_quote_status' => false,
1319 'retweet_count' => 0,
1320 'favorite_count' => 0,
1321 'favorited' => $lastwall['starred'] ? true : false,
1322 'retweeted' => false,
1323 'possibly_sensitive' => false,
1325 'statusnet_html' => $converted["html"],
1326 'statusnet_conversation_id' => $lastwall['parent'],
1327 'external_url' => System::baseUrl() . '/display/' . $lastwall['guid'],
1330 if (count($converted["attachments"]) > 0) {
1331 $status_info["attachments"] = $converted["attachments"];
1334 if (count($converted["entities"]) > 0) {
1335 $status_info["entities"] = $converted["entities"];
1338 if ($status_info["source"] == 'web') {
1339 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1340 } elseif (ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) != $status_info["source"]) {
1341 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']).')');
1344 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1345 unset($status_info["user"]["uid"]);
1346 unset($status_info["user"]["self"]);
1348 Logger::log('status_info: '.print_r($status_info, true), Logger::DEBUG);
1350 if ($type == "raw") {
1351 return $status_info;
1354 return api_format_data("statuses", $type, ['status' => $status_info]);
1359 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1360 * The author's most recent status will be returned inline.
1362 * @param string $type Return type (atom, rss, xml, json)
1363 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1365 function api_users_show($type)
1369 $user_info = api_get_user($a);
1371 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1372 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'private' => false];
1373 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1375 if (DBA::isResult($lastwall)) {
1376 $in_reply_to = api_in_reply_to($lastwall);
1378 $converted = api_convert_item($lastwall);
1380 if ($type == "xml") {
1381 $geo = "georss:point";
1386 $user_info['status'] = [
1387 'text' => $converted["text"],
1388 'truncated' => false,
1389 'created_at' => api_date($lastwall['created']),
1390 'in_reply_to_status_id' => $in_reply_to['status_id'],
1391 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1392 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1393 'id' => intval($lastwall['contact-id']),
1394 'id_str' => (string) $lastwall['contact-id'],
1395 'in_reply_to_user_id' => $in_reply_to['user_id'],
1396 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1397 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1399 'favorited' => $lastwall['starred'] ? true : false,
1400 'statusnet_html' => $converted["html"],
1401 'statusnet_conversation_id' => $lastwall['parent'],
1402 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1405 if (count($converted["attachments"]) > 0) {
1406 $user_info["status"]["attachments"] = $converted["attachments"];
1409 if (count($converted["entities"]) > 0) {
1410 $user_info["status"]["entities"] = $converted["entities"];
1413 if ($user_info["status"]["source"] == 'web') {
1414 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1417 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1418 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) . ')');
1422 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1423 unset($user_info["uid"]);
1424 unset($user_info["self"]);
1426 return api_format_data("user", $type, ['user' => $user_info]);
1429 /// @TODO move to top of file or somewhere better
1430 api_register_func('api/users/show', 'api_users_show');
1431 api_register_func('api/externalprofile/show', 'api_users_show');
1434 * Search a public user account.
1436 * @param string $type Return type (atom, rss, xml, json)
1438 * @return array|string
1439 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1441 function api_users_search($type)
1447 if (!empty($_GET['q'])) {
1448 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1450 if (!DBA::isResult($r)) {
1451 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1454 if (DBA::isResult($r)) {
1456 foreach ($r as $user) {
1457 $user_info = api_get_user($a, $user["id"]);
1459 if ($type == "xml") {
1460 $userlist[$k++.":user"] = $user_info;
1462 $userlist[] = $user_info;
1465 $userlist = ["users" => $userlist];
1467 throw new BadRequestException("User ".$_GET["q"]." not found.");
1470 throw new BadRequestException("No user specified.");
1473 return api_format_data("users", $type, $userlist);
1476 /// @TODO move to top of file or somewhere better
1477 api_register_func('api/users/search', 'api_users_search');
1480 * Return user objects
1482 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1484 * @param string $type Return format: json or xml
1486 * @return array|string
1487 * @throws NotFoundException if the results are empty.
1489 function api_users_lookup($type)
1493 if (!empty($_REQUEST['user_id'])) {
1494 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1496 $users[] = api_get_user(get_app(), $id);
1501 if (empty($users)) {
1502 throw new NotFoundException;
1505 return api_format_data("users", $type, ['users' => $users]);
1508 /// @TODO move to top of file or somewhere better
1509 api_register_func('api/users/lookup', 'api_users_lookup', true);
1512 * Returns statuses that match a specified query.
1514 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1516 * @param string $type Return format: json, xml, atom, rss
1518 * @return array|string
1519 * @throws BadRequestException if the "q" parameter is missing.
1521 function api_search($type)
1524 $user_info = api_get_user($a);
1526 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1528 if (empty($_REQUEST['q'])) { throw new BadRequestException('q parameter is required.'); }
1530 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1533 $data['status'] = [];
1535 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1536 if (!empty($_REQUEST['rpp'])) {
1537 $count = $_REQUEST['rpp'];
1538 } elseif (!empty($_REQUEST['count'])) {
1539 $count = $_REQUEST['count'];
1542 $since_id = defaults($_REQUEST, 'since_id', 0);
1543 $max_id = defaults($_REQUEST, 'max_id', 0);
1544 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1545 $start = $page * $count;
1546 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1547 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1548 $searchTerm = $matches[1];
1549 $condition = ["`oid` > ?
1550 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1551 AND `otype` = ? AND `type` = ? AND `term` = ?",
1552 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1554 $condition[0] .= ' AND `oid` <= ?';
1555 $condition[] = $max_id;
1557 $terms = DBA::select('term', ['oid'], $condition, []);
1559 while ($term = DBA::fetch($terms)) {
1560 $itemIds[] = $term['oid'];
1564 if (empty($itemIds)) {
1565 return api_format_data('statuses', $type, $data);
1568 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1569 if ($exclude_replies) {
1570 $preCondition[] = '`id` = `parent`';
1573 $condition = [implode(' AND ', $preCondition)];
1575 $condition = ["`id` > ?
1576 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1577 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1578 AND `body` LIKE CONCAT('%',?,'%')",
1579 $since_id, api_user(), $_REQUEST['q']];
1581 $condition[0] .= ' AND `id` <= ?';
1582 $condition[] = $max_id;
1586 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1588 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1590 bindComments($data['status']);
1592 return api_format_data('statuses', $type, $data);
1595 /// @TODO move to top of file or somewhere better
1596 api_register_func('api/search/tweets', 'api_search', true);
1597 api_register_func('api/search', 'api_search', true);
1600 * Returns the most recent statuses posted by the user and the users they follow.
1602 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1604 * @param string $type Return type (atom, rss, xml, json)
1606 * @todo Optional parameters
1607 * @todo Add reply info
1609 function api_statuses_home_timeline($type)
1612 $user_info = api_get_user($a);
1614 if (api_user() === false || $user_info === false) {
1615 throw new ForbiddenException();
1618 unset($_REQUEST["user_id"]);
1619 unset($_GET["user_id"]);
1621 unset($_REQUEST["screen_name"]);
1622 unset($_GET["screen_name"]);
1624 // get last network messages
1627 $count = defaults($_REQUEST, 'count', 20);
1628 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1632 $since_id = defaults($_REQUEST, 'since_id', 0);
1633 $max_id = defaults($_REQUEST, 'max_id', 0);
1634 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1635 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1637 $start = $page * $count;
1639 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1640 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1643 $condition[0] .= " AND `item`.`id` <= ?";
1644 $condition[] = $max_id;
1646 if ($exclude_replies) {
1647 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1649 if ($conversation_id > 0) {
1650 $condition[0] .= " AND `item`.`parent` = ?";
1651 $condition[] = $conversation_id;
1654 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1655 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1657 $items = Item::inArray($statuses);
1659 $ret = api_format_items($items, $user_info, false, $type);
1661 // Set all posts from the query above to seen
1663 foreach ($items as $item) {
1664 $idarray[] = intval($item["id"]);
1667 if (!empty($idarray)) {
1668 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1670 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1676 $data = ['status' => $ret];
1681 $data = api_rss_extra($a, $data, $user_info);
1685 return api_format_data("statuses", $type, $data);
1689 /// @TODO move to top of file or somewhere better
1690 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1691 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1694 * Returns the most recent statuses from public users.
1696 * @param string $type Return type (atom, rss, xml, json)
1698 * @return array|string
1700 function api_statuses_public_timeline($type)
1703 $user_info = api_get_user($a);
1705 if (api_user() === false || $user_info === false) {
1706 throw new ForbiddenException();
1709 // get last network messages
1712 $count = defaults($_REQUEST, 'count', 20);
1713 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1717 $since_id = defaults($_REQUEST, 'since_id', 0);
1718 $max_id = defaults($_REQUEST, 'max_id', 0);
1719 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1720 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1722 $start = $page * $count;
1724 if ($exclude_replies && !$conversation_id) {
1725 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1726 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1729 $condition[0] .= " AND `thread`.`iid` <= ?";
1730 $condition[] = $max_id;
1733 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1734 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1736 $r = Item::inArray($statuses);
1738 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1739 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1742 $condition[0] .= " AND `item`.`id` <= ?";
1743 $condition[] = $max_id;
1745 if ($conversation_id > 0) {
1746 $condition[0] .= " AND `item`.`parent` = ?";
1747 $condition[] = $conversation_id;
1750 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1751 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1753 $r = Item::inArray($statuses);
1756 $ret = api_format_items($r, $user_info, false, $type);
1760 $data = ['status' => $ret];
1765 $data = api_rss_extra($a, $data, $user_info);
1769 return api_format_data("statuses", $type, $data);
1772 /// @TODO move to top of file or somewhere better
1773 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1776 * Returns the most recent statuses posted by users this node knows about.
1778 * @brief Returns the list of public federated posts this node knows about
1780 * @param string $type Return format: json, xml, atom, rss
1781 * @return array|string
1782 * @throws ForbiddenException
1784 function api_statuses_networkpublic_timeline($type)
1787 $user_info = api_get_user($a);
1789 if (api_user() === false || $user_info === false) {
1790 throw new ForbiddenException();
1793 $since_id = defaults($_REQUEST, 'since_id', 0);
1794 $max_id = defaults($_REQUEST, 'max_id', 0);
1797 $count = defaults($_REQUEST, 'count', 20);
1798 $page = defaults($_REQUEST, 'page', 1);
1802 $start = ($page - 1) * $count;
1804 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1805 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1808 $condition[0] .= " AND `thread`.`iid` <= ?";
1809 $condition[] = $max_id;
1812 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1813 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1815 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1819 $data = ['status' => $ret];
1824 $data = api_rss_extra($a, $data, $user_info);
1828 return api_format_data("statuses", $type, $data);
1831 /// @TODO move to top of file or somewhere better
1832 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1835 * Returns a single status.
1837 * @param string $type Return type (atom, rss, xml, json)
1839 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1841 function api_statuses_show($type)
1844 $user_info = api_get_user($a);
1846 if (api_user() === false || $user_info === false) {
1847 throw new ForbiddenException();
1851 $id = intval(defaults($a->argv, 3, 0));
1854 $id = intval(defaults($_REQUEST, 'id', 0));
1859 $id = intval(defaults($a->argv, 4, 0));
1862 Logger::log('API: api_statuses_show: ' . $id);
1864 $conversation = !empty($_REQUEST['conversation']);
1866 // try to fetch the item for the local user - or the public item, if there is no local one
1867 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1868 if (!DBA::isResult($uri_item)) {
1869 throw new BadRequestException("There is no status with this id.");
1872 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1873 if (!DBA::isResult($item)) {
1874 throw new BadRequestException("There is no status with this id.");
1879 if ($conversation) {
1880 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1881 $params = ['order' => ['id' => true]];
1883 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1887 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1889 /// @TODO How about copying this to above methods which don't check $r ?
1890 if (!DBA::isResult($statuses)) {
1891 throw new BadRequestException("There is no status with this id.");
1894 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1896 if ($conversation) {
1897 $data = ['status' => $ret];
1898 return api_format_data("statuses", $type, $data);
1900 $data = ['status' => $ret[0]];
1901 return api_format_data("status", $type, $data);
1905 /// @TODO move to top of file or somewhere better
1906 api_register_func('api/statuses/show', 'api_statuses_show', true);
1910 * @param string $type Return type (atom, rss, xml, json)
1912 * @todo nothing to say?
1914 function api_conversation_show($type)
1917 $user_info = api_get_user($a);
1919 if (api_user() === false || $user_info === false) {
1920 throw new ForbiddenException();
1924 $id = intval(defaults($a->argv , 3 , 0));
1925 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1926 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1927 $count = intval(defaults($_REQUEST, 'count' , 20));
1928 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1933 $start = $page * $count;
1936 $id = intval(defaults($_REQUEST, 'id', 0));
1941 $id = intval(defaults($a->argv, 4, 0));
1944 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1946 // try to fetch the item for the local user - or the public item, if there is no local one
1947 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1948 if (!DBA::isResult($item)) {
1949 throw new BadRequestException("There is no status with this id.");
1952 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1953 if (!DBA::isResult($parent)) {
1954 throw new BadRequestException("There is no status with this id.");
1957 $id = $parent['id'];
1959 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1960 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1963 $condition[0] .= " AND `item`.`id` <= ?";
1964 $condition[] = $max_id;
1967 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1968 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1970 if (!DBA::isResult($statuses)) {
1971 throw new BadRequestException("There is no status with id $id.");
1974 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1976 $data = ['status' => $ret];
1977 return api_format_data("statuses", $type, $data);
1980 /// @TODO move to top of file or somewhere better
1981 api_register_func('api/conversation/show', 'api_conversation_show', true);
1982 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1987 * @param string $type Return type (atom, rss, xml, json)
1989 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1991 function api_statuses_repeat($type)
1997 if (api_user() === false) {
1998 throw new ForbiddenException();
2004 $id = intval(defaults($a->argv, 3, 0));
2007 $id = intval(defaults($_REQUEST, 'id', 0));
2012 $id = intval(defaults($a->argv, 4, 0));
2015 Logger::log('API: api_statuses_repeat: '.$id);
2017 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2018 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2020 if (DBA::isResult($item) && $item['body'] != "") {
2021 if (strpos($item['body'], "[/share]") !== false) {
2022 $pos = strpos($item['body'], "[share");
2023 $post = substr($item['body'], $pos);
2025 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2027 $post .= $item['body'];
2028 $post .= "[/share]";
2030 $_REQUEST['body'] = $post;
2031 $_REQUEST['profile_uid'] = api_user();
2032 $_REQUEST['api_source'] = true;
2034 if (empty($_REQUEST['source'])) {
2035 $_REQUEST["source"] = api_source();
2038 $item_id = item_post($a);
2040 throw new ForbiddenException();
2043 // output the post that we just posted.
2045 return api_status_show($type, $item_id);
2048 /// @TODO move to top of file or somewhere better
2049 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2052 * Destroys a specific status.
2054 * @param string $type Return type (atom, rss, xml, json)
2056 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2058 function api_statuses_destroy($type)
2062 if (api_user() === false) {
2063 throw new ForbiddenException();
2069 $id = intval(defaults($a->argv, 3, 0));
2072 $id = intval(defaults($_REQUEST, 'id', 0));
2077 $id = intval(defaults($a->argv, 4, 0));
2080 Logger::log('API: api_statuses_destroy: '.$id);
2082 $ret = api_statuses_show($type);
2084 Item::deleteForUser(['id' => $id], api_user());
2089 /// @TODO move to top of file or somewhere better
2090 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2093 * Returns the most recent mentions.
2095 * @param string $type Return type (atom, rss, xml, json)
2097 * @see http://developer.twitter.com/doc/get/statuses/mentions
2099 function api_statuses_mentions($type)
2102 $user_info = api_get_user($a);
2104 if (api_user() === false || $user_info === false) {
2105 throw new ForbiddenException();
2108 unset($_REQUEST["user_id"]);
2109 unset($_GET["user_id"]);
2111 unset($_REQUEST["screen_name"]);
2112 unset($_GET["screen_name"]);
2114 // get last network messages
2117 $since_id = defaults($_REQUEST, 'since_id', 0);
2118 $max_id = defaults($_REQUEST, 'max_id' , 0);
2119 $count = defaults($_REQUEST, 'count' , 20);
2120 $page = defaults($_REQUEST, 'page' , 1);
2125 $start = ($page - 1) * $count;
2127 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2128 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2129 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2132 $condition[0] .= " AND `item`.`id` <= ?";
2133 $condition[] = $max_id;
2136 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2137 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2139 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2141 $data = ['status' => $ret];
2146 $data = api_rss_extra($a, $data, $user_info);
2150 return api_format_data("statuses", $type, $data);
2153 /// @TODO move to top of file or somewhere better
2154 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2155 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2158 * Returns the most recent statuses posted by the user.
2160 * @brief Returns a user's public timeline
2162 * @param string $type Either "json" or "xml"
2163 * @return string|array
2164 * @throws ForbiddenException
2165 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2167 function api_statuses_user_timeline($type)
2170 $user_info = api_get_user($a);
2172 if (api_user() === false || $user_info === false) {
2173 throw new ForbiddenException();
2177 "api_statuses_user_timeline: api_user: ". api_user() .
2178 "\nuser_info: ".print_r($user_info, true) .
2179 "\n_REQUEST: ".print_r($_REQUEST, true),
2183 $since_id = defaults($_REQUEST, 'since_id', 0);
2184 $max_id = defaults($_REQUEST, 'max_id', 0);
2185 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2186 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2189 $count = defaults($_REQUEST, 'count', 20);
2190 $page = defaults($_REQUEST, 'page', 1);
2194 $start = ($page - 1) * $count;
2196 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2197 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2199 if ($user_info['self'] == 1) {
2200 $condition[0] .= ' AND `item`.`wall` ';
2203 if ($exclude_replies) {
2204 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2207 if ($conversation_id > 0) {
2208 $condition[0] .= " AND `item`.`parent` = ?";
2209 $condition[] = $conversation_id;
2213 $condition[0] .= " AND `item`.`id` <= ?";
2214 $condition[] = $max_id;
2217 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2218 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2220 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2224 $data = ['status' => $ret];
2229 $data = api_rss_extra($a, $data, $user_info);
2233 return api_format_data("statuses", $type, $data);
2236 /// @TODO move to top of file or somewhere better
2237 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2240 * Star/unstar an item.
2241 * param: id : id of the item
2243 * @param string $type Return type (atom, rss, xml, json)
2245 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2247 function api_favorites_create_destroy($type)
2251 if (api_user() === false) {
2252 throw new ForbiddenException();
2255 // for versioned api.
2256 /// @TODO We need a better global soluton
2257 $action_argv_id = 2;
2258 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2259 $action_argv_id = 3;
2262 if ($a->argc <= $action_argv_id) {
2263 throw new BadRequestException("Invalid request.");
2265 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2266 if ($a->argc == $action_argv_id + 2) {
2267 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2269 $itemid = intval(defaults($_REQUEST, 'id', 0));
2272 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2274 if (!DBA::isResult($item)) {
2275 throw new BadRequestException("Invalid item.");
2280 $item['starred'] = 1;
2283 $item['starred'] = 0;
2286 throw new BadRequestException("Invalid action ".$action);
2289 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2292 throw new InternalServerErrorException("DB error");
2296 $user_info = api_get_user($a);
2297 $rets = api_format_items([$item], $user_info, false, $type);
2300 $data = ['status' => $ret];
2305 $data = api_rss_extra($a, $data, $user_info);
2309 return api_format_data("status", $type, $data);
2312 /// @TODO move to top of file or somewhere better
2313 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2314 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2317 * Returns the most recent favorite statuses.
2319 * @param string $type Return type (atom, rss, xml, json)
2321 * @return string|array
2323 function api_favorites($type)
2328 $user_info = api_get_user($a);
2330 if (api_user() === false || $user_info === false) {
2331 throw new ForbiddenException();
2336 // in friendica starred item are private
2337 // return favorites only for self
2338 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2340 if ($user_info['self'] == 0) {
2344 $since_id = defaults($_REQUEST, 'since_id', 0);
2345 $max_id = defaults($_REQUEST, 'max_id', 0);
2346 $count = defaults($_GET, 'count', 20);
2347 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2352 $start = $page*$count;
2354 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2355 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2357 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2360 $condition[0] .= " AND `item`.`id` <= ?";
2361 $condition[] = $max_id;
2364 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2366 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2371 $data = ['status' => $ret];
2376 $data = api_rss_extra($a, $data, $user_info);
2380 return api_format_data("statuses", $type, $data);
2383 /// @TODO move to top of file or somewhere better
2384 api_register_func('api/favorites', 'api_favorites', true);
2388 * @param array $item
2389 * @param array $recipient
2390 * @param array $sender
2394 function api_format_messages($item, $recipient, $sender)
2396 // standard meta information
2398 'id' => $item['id'],
2399 'sender_id' => $sender['id'],
2401 'recipient_id' => $recipient['id'],
2402 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2403 'sender_screen_name' => $sender['screen_name'],
2404 'recipient_screen_name' => $recipient['screen_name'],
2405 'sender' => $sender,
2406 'recipient' => $recipient,
2408 'friendica_seen' => defaults($item, 'seen', 0),
2409 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2412 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2413 if (isset($ret['sender']['uid'])) {
2414 unset($ret['sender']['uid']);
2416 if (isset($ret['sender']['self'])) {
2417 unset($ret['sender']['self']);
2419 if (isset($ret['recipient']['uid'])) {
2420 unset($ret['recipient']['uid']);
2422 if (isset($ret['recipient']['self'])) {
2423 unset($ret['recipient']['self']);
2426 //don't send title to regular StatusNET requests to avoid confusing these apps
2427 if (!empty($_GET['getText'])) {
2428 $ret['title'] = $item['title'];
2429 if ($_GET['getText'] == 'html') {
2430 $ret['text'] = BBCode::convert($item['body'], false);
2431 } elseif ($_GET['getText'] == 'plain') {
2432 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2435 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2437 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2438 unset($ret['sender']);
2439 unset($ret['recipient']);
2447 * @param array $item
2451 function api_convert_item($item)
2453 $body = $item['body'];
2454 $attachments = api_get_attachments($body);
2456 // Workaround for ostatus messages where the title is identically to the body
2457 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2458 $statusbody = trim(HTML::toPlaintext($html, 0));
2460 // handle data: images
2461 $statusbody = api_format_items_embeded_images($item, $statusbody);
2463 $statustitle = trim($item['title']);
2465 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2466 $statustext = trim($statusbody);
2468 $statustext = trim($statustitle."\n\n".$statusbody);
2471 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
2472 $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2475 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2477 // Workaround for clients with limited HTML parser functionality
2478 $search = ["<br>", "<blockquote>", "</blockquote>",
2479 "<h1>", "</h1>", "<h2>", "</h2>",
2480 "<h3>", "</h3>", "<h4>", "</h4>",
2481 "<h5>", "</h5>", "<h6>", "</h6>"];
2482 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2483 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2484 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2485 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2486 $statushtml = str_replace($search, $replace, $statushtml);
2488 if ($item['title'] != "") {
2489 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2493 $oldtext = $statushtml;
2494 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2495 } while ($oldtext != $statushtml);
2497 if (substr($statushtml, 0, 4) == '<br>') {
2498 $statushtml = substr($statushtml, 4);
2501 if (substr($statushtml, 0, -4) == '<br>') {
2502 $statushtml = substr($statushtml, -4);
2505 // feeds without body should contain the link
2506 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2507 $statushtml .= BBCode::convert($item['plink']);
2510 $entities = api_get_entitities($statustext, $body);
2513 "text" => $statustext,
2514 "html" => $statushtml,
2515 "attachments" => $attachments,
2516 "entities" => $entities
2522 * @param string $body
2526 function api_get_attachments(&$body)
2529 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2531 $URLSearchString = "^\[\]";
2532 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2540 foreach ($images[1] as $image) {
2541 $imagedata = Image::getInfoFromURL($image);
2544 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2548 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2549 foreach ($images[0] as $orig) {
2550 $body = str_replace($orig, "", $body);
2554 return $attachments;
2559 * @param string $text
2560 * @param string $bbcode
2563 * @todo Links at the first character of the post
2565 function api_get_entitities(&$text, $bbcode)
2567 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2569 if ($include_entities != "true") {
2570 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2572 foreach ($images[1] as $image) {
2573 $replace = ProxyUtils::proxifyUrl($image);
2574 $text = str_replace($image, $replace, $text);
2579 $bbcode = BBCode::cleanPictureLinks($bbcode);
2581 // Change pure links in text to bbcode uris
2582 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2585 $entities["hashtags"] = [];
2586 $entities["symbols"] = [];
2587 $entities["urls"] = [];
2588 $entities["user_mentions"] = [];
2590 $URLSearchString = "^\[\]";
2592 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2594 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2595 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2596 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2598 $bbcode = preg_replace(
2599 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2600 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2603 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2605 $bbcode = preg_replace(
2606 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2607 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2610 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2612 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2614 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2615 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2618 foreach ($urls[1] as $id => $url) {
2619 //$start = strpos($text, $url, $offset);
2620 $start = iconv_strpos($text, $url, 0, "UTF-8");
2621 if (!($start === false)) {
2622 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2626 ksort($ordered_urls);
2629 //foreach ($urls[1] AS $id=>$url) {
2630 foreach ($ordered_urls as $url) {
2631 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2632 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2634 $display_url = $url["title"];
2636 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2637 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2639 if (strlen($display_url) > 26) {
2640 $display_url = substr($display_url, 0, 25)."…";
2644 //$start = strpos($text, $url, $offset);
2645 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2646 if (!($start === false)) {
2647 $entities["urls"][] = ["url" => $url["url"],
2648 "expanded_url" => $url["url"],
2649 "display_url" => $display_url,
2650 "indices" => [$start, $start+strlen($url["url"])]];
2651 $offset = $start + 1;
2655 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2656 $ordered_images = [];
2657 foreach ($images[1] as $image) {
2658 //$start = strpos($text, $url, $offset);
2659 $start = iconv_strpos($text, $image, 0, "UTF-8");
2660 if (!($start === false)) {
2661 $ordered_images[$start] = $image;
2664 //$entities["media"] = array();
2667 foreach ($ordered_images as $url) {
2668 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2669 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2671 if (strlen($display_url) > 26) {
2672 $display_url = substr($display_url, 0, 25)."…";
2675 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2676 if (!($start === false)) {
2677 $image = Image::getInfoFromURL($url);
2679 // If image cache is activated, then use the following sizes:
2680 // thumb (150), small (340), medium (600) and large (1024)
2681 if (!Config::get("system", "proxy_disabled")) {
2682 $media_url = ProxyUtils::proxifyUrl($url);
2685 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2686 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2688 if (($image[0] > 150) || ($image[1] > 150)) {
2689 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2690 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2693 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2694 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2696 if (($image[0] > 600) || ($image[1] > 600)) {
2697 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2698 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2702 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2705 $entities["media"][] = [
2707 "id_str" => (string)$start+1,
2708 "indices" => [$start, $start+strlen($url)],
2709 "media_url" => Strings::normaliseLink($media_url),
2710 "media_url_https" => $media_url,
2712 "display_url" => $display_url,
2713 "expanded_url" => $url,
2717 $offset = $start + 1;
2726 * @param array $item
2727 * @param string $text
2731 function api_format_items_embeded_images($item, $text)
2733 $text = preg_replace_callback(
2734 '|data:image/([^;]+)[^=]+=*|m',
2735 function () use ($item) {
2736 return System::baseUrl() . '/display/' . $item['guid'];
2744 * @brief return <a href='url'>name</a> as array
2746 * @param string $txt text
2751 function api_contactlink_to_array($txt)
2754 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2755 if ($r && count($match)==3) {
2757 'name' => $match[2],
2771 * @brief return likes, dislikes and attend status for item
2773 * @param array $item array
2774 * @param string $type Return type (atom, rss, xml, json)
2777 * likes => int count,
2778 * dislikes => int count
2780 function api_format_items_activities($item, $type = "json")
2789 'attendmaybe' => [],
2792 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2793 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2795 while ($parent_item = Item::fetch($ret)) {
2796 // not used as result should be structured like other user data
2797 //builtin_activity_puller($i, $activities);
2799 // get user data and add it to the array of the activity
2800 $user = api_get_user($a, $parent_item['author-id']);
2801 switch ($parent_item['verb']) {
2803 $activities['like'][] = $user;
2805 case ACTIVITY_DISLIKE:
2806 $activities['dislike'][] = $user;
2808 case ACTIVITY_ATTEND:
2809 $activities['attendyes'][] = $user;
2811 case ACTIVITY_ATTENDNO:
2812 $activities['attendno'][] = $user;
2814 case ACTIVITY_ATTENDMAYBE:
2815 $activities['attendmaybe'][] = $user;
2824 if ($type == "xml") {
2825 $xml_activities = [];
2826 foreach ($activities as $k => $v) {
2827 // change xml element from "like" to "friendica:like"
2828 $xml_activities["friendica:".$k] = $v;
2829 // add user data into xml output
2831 foreach ($v as $user) {
2832 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2835 $activities = $xml_activities;
2843 * @brief return data from profiles
2845 * @param array $profile_row array containing data from db table 'profile'
2848 function api_format_items_profiles($profile_row)
2851 'profile_id' => $profile_row['id'],
2852 'profile_name' => $profile_row['profile-name'],
2853 'is_default' => $profile_row['is-default'] ? true : false,
2854 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2855 'profile_photo' => $profile_row['photo'],
2856 'profile_thumb' => $profile_row['thumb'],
2857 'publish' => $profile_row['publish'] ? true : false,
2858 'net_publish' => $profile_row['net-publish'] ? true : false,
2859 'description' => $profile_row['pdesc'],
2860 'date_of_birth' => $profile_row['dob'],
2861 'address' => $profile_row['address'],
2862 'city' => $profile_row['locality'],
2863 'region' => $profile_row['region'],
2864 'postal_code' => $profile_row['postal-code'],
2865 'country' => $profile_row['country-name'],
2866 'hometown' => $profile_row['hometown'],
2867 'gender' => $profile_row['gender'],
2868 'marital' => $profile_row['marital'],
2869 'marital_with' => $profile_row['with'],
2870 'marital_since' => $profile_row['howlong'],
2871 'sexual' => $profile_row['sexual'],
2872 'politic' => $profile_row['politic'],
2873 'religion' => $profile_row['religion'],
2874 'public_keywords' => $profile_row['pub_keywords'],
2875 'private_keywords' => $profile_row['prv_keywords'],
2876 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2877 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2878 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2879 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2880 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2881 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2882 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2883 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2884 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2885 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2886 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2887 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2888 'homepage' => $profile_row['homepage'],
2895 * @brief format items to be returned by api
2897 * @param array $r array of items
2898 * @param array $user_info
2899 * @param bool $filter_user filter items by $user_info
2900 * @param string $type Return type (atom, rss, xml, json)
2902 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2908 foreach ((array)$r as $item) {
2909 localize_item($item);
2910 list($status_user, $owner_user) = api_item_get_user($a, $item);
2912 // Look if the posts are matching if they should be filtered by user id
2913 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2917 $in_reply_to = api_in_reply_to($item);
2919 $converted = api_convert_item($item);
2921 if ($type == "xml") {
2922 $geo = "georss:point";
2928 'text' => $converted["text"],
2929 'truncated' => false,
2930 'created_at'=> api_date($item['created']),
2931 'in_reply_to_status_id' => $in_reply_to['status_id'],
2932 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2933 'source' => (($item['app']) ? $item['app'] : 'web'),
2934 'id' => intval($item['id']),
2935 'id_str' => (string) intval($item['id']),
2936 'in_reply_to_user_id' => $in_reply_to['user_id'],
2937 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2938 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2940 'favorited' => $item['starred'] ? true : false,
2941 'user' => $status_user,
2942 'friendica_owner' => $owner_user,
2943 'friendica_private' => $item['private'] == 1,
2944 //'entities' => NULL,
2945 'statusnet_html' => $converted["html"],
2946 'statusnet_conversation_id' => $item['parent'],
2947 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2948 'friendica_activities' => api_format_items_activities($item, $type),
2951 if (count($converted["attachments"]) > 0) {
2952 $status["attachments"] = $converted["attachments"];
2955 if (count($converted["entities"]) > 0) {
2956 $status["entities"] = $converted["entities"];
2959 if ($status["source"] == 'web') {
2960 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
2961 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
2962 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
2965 if ($item["id"] == $item["parent"]) {
2966 $retweeted_item = api_share_as_retweet($item);
2967 if ($retweeted_item !== false) {
2968 $retweeted_status = $status;
2969 $status['user'] = $status['friendica_owner'];
2971 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
2972 } catch (BadRequestException $e) {
2973 // user not found. should be found?
2974 /// @todo check if the user should be always found
2975 $retweeted_status["user"] = [];
2978 $rt_converted = api_convert_item($retweeted_item);
2980 $retweeted_status['text'] = $rt_converted["text"];
2981 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2982 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2983 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2984 $status['retweeted_status'] = $retweeted_status;
2988 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2989 unset($status["user"]["uid"]);
2990 unset($status["user"]["self"]);
2992 if ($item["coord"] != "") {
2993 $coords = explode(' ', $item["coord"]);
2994 if (count($coords) == 2) {
2995 if ($type == "json") {
2996 $status["geo"] = ['type' => 'Point',
2997 'coordinates' => [(float) $coords[0],
2998 (float) $coords[1]]];
2999 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3000 $status["georss:point"] = $item["coord"];
3010 * Returns the remaining number of API requests available to the user before the API limit is reached.
3012 * @param string $type Return type (atom, rss, xml, json)
3014 * @return array|string
3016 function api_account_rate_limit_status($type)
3018 if ($type == "xml") {
3020 'remaining-hits' => '150',
3021 '@attributes' => ["type" => "integer"],
3022 'hourly-limit' => '150',
3023 '@attributes2' => ["type" => "integer"],
3024 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3025 '@attributes3' => ["type" => "datetime"],
3026 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3027 '@attributes4' => ["type" => "integer"],
3031 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3032 'remaining_hits' => '150',
3033 'hourly_limit' => '150',
3034 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3038 return api_format_data('hash', $type, ['hash' => $hash]);
3041 /// @TODO move to top of file or somewhere better
3042 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3045 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3047 * @param string $type Return type (atom, rss, xml, json)
3049 * @return array|string
3051 function api_help_test($type)
3053 if ($type == 'xml') {
3059 return api_format_data('ok', $type, ["ok" => $ok]);
3062 /// @TODO move to top of file or somewhere better
3063 api_register_func('api/help/test', 'api_help_test', false);
3066 * Returns all lists the user subscribes to.
3068 * @param string $type Return type (atom, rss, xml, json)
3070 * @return array|string
3071 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3073 function api_lists_list($type)
3076 /// @TODO $ret is not filled here?
3077 return api_format_data('lists', $type, ["lists_list" => $ret]);
3080 /// @TODO move to top of file or somewhere better
3081 api_register_func('api/lists/list', 'api_lists_list', true);
3082 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3085 * Returns all groups the user owns.
3087 * @param string $type Return type (atom, rss, xml, json)
3089 * @return array|string
3090 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3092 function api_lists_ownerships($type)
3096 if (api_user() === false) {
3097 throw new ForbiddenException();
3101 $user_info = api_get_user($a);
3102 $uid = $user_info['uid'];
3104 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3106 // loop through all groups
3108 foreach ($groups as $group) {
3109 if ($group['visible']) {
3115 'name' => $group['name'],
3116 'id' => intval($group['id']),
3117 'id_str' => (string) $group['id'],
3118 'user' => $user_info,
3122 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3125 /// @TODO move to top of file or somewhere better
3126 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3129 * Returns recent statuses from users in the specified group.
3131 * @param string $type Return type (atom, rss, xml, json)
3133 * @return array|string
3134 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3136 function api_lists_statuses($type)
3140 $user_info = api_get_user($a);
3141 if (api_user() === false || $user_info === false) {
3142 throw new ForbiddenException();
3145 unset($_REQUEST["user_id"]);
3146 unset($_GET["user_id"]);
3148 unset($_REQUEST["screen_name"]);
3149 unset($_GET["screen_name"]);
3151 if (empty($_REQUEST['list_id'])) {
3152 throw new BadRequestException('list_id not specified');
3156 $count = defaults($_REQUEST, 'count', 20);
3157 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3161 $since_id = defaults($_REQUEST, 'since_id', 0);
3162 $max_id = defaults($_REQUEST, 'max_id', 0);
3163 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3164 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3166 $start = $page * $count;
3168 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3169 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3172 $condition[0] .= " AND `item`.`id` <= ?";
3173 $condition[] = $max_id;
3175 if ($exclude_replies > 0) {
3176 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3178 if ($conversation_id > 0) {
3179 $condition[0] .= " AND `item`.`parent` = ?";
3180 $condition[] = $conversation_id;
3183 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3184 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3186 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3188 $data = ['status' => $items];
3193 $data = api_rss_extra($a, $data, $user_info);
3197 return api_format_data("statuses", $type, $data);
3200 /// @TODO move to top of file or somewhere better
3201 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3204 * Considers friends and followers lists to be private and won't return
3205 * anything if any user_id parameter is passed.
3207 * @brief Returns either the friends of the follower list
3209 * @param string $qtype Either "friends" or "followers"
3210 * @return boolean|array
3211 * @throws ForbiddenException
3213 function api_statuses_f($qtype)
3217 if (api_user() === false) {
3218 throw new ForbiddenException();
3222 $count = defaults($_GET, 'count', 20);
3223 $page = defaults($_GET, 'page', 1);
3227 $start = ($page - 1) * $count;
3229 $user_info = api_get_user($a);
3231 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3232 /* this is to stop Hotot to load friends multiple times
3233 * I'm not sure if I'm missing return something or
3234 * is a bug in hotot. Workaround, meantime
3238 return array('$users' => $ret);*/
3243 if ($qtype == 'friends') {
3244 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3245 } elseif ($qtype == 'followers') {
3246 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3249 // friends and followers only for self
3250 if ($user_info['self'] == 0) {
3251 $sql_extra = " AND false ";
3254 if ($qtype == 'blocks') {
3255 $sql_filter = 'AND `blocked` AND NOT `pending`';
3256 } elseif ($qtype == 'incoming') {
3257 $sql_filter = 'AND `pending`';
3259 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3277 foreach ($r as $cid) {
3278 $user = api_get_user($a, $cid['nurl']);
3279 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3280 unset($user["uid"]);
3281 unset($user["self"]);
3288 return ['user' => $ret];
3293 * Returns the user's friends.
3295 * @brief Returns the list of friends of the provided user
3297 * @deprecated By Twitter API in favor of friends/list
3299 * @param string $type Either "json" or "xml"
3300 * @return boolean|string|array
3302 function api_statuses_friends($type)
3304 $data = api_statuses_f("friends");
3305 if ($data === false) {
3308 return api_format_data("users", $type, $data);
3312 * Returns the user's followers.
3314 * @brief Returns the list of followers of the provided user
3316 * @deprecated By Twitter API in favor of friends/list
3318 * @param string $type Either "json" or "xml"
3319 * @return boolean|string|array
3321 function api_statuses_followers($type)
3323 $data = api_statuses_f("followers");
3324 if ($data === false) {
3327 return api_format_data("users", $type, $data);
3330 /// @TODO move to top of file or somewhere better
3331 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3332 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3335 * Returns the list of blocked users
3337 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3339 * @param string $type Either "json" or "xml"
3341 * @return boolean|string|array
3343 function api_blocks_list($type)
3345 $data = api_statuses_f('blocks');
3346 if ($data === false) {
3349 return api_format_data("users", $type, $data);
3352 /// @TODO move to top of file or somewhere better
3353 api_register_func('api/blocks/list', 'api_blocks_list', true);
3356 * Returns the list of pending users IDs
3358 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3360 * @param string $type Either "json" or "xml"
3362 * @return boolean|string|array
3364 function api_friendships_incoming($type)
3366 $data = api_statuses_f('incoming');
3367 if ($data === false) {
3372 foreach ($data['user'] as $user) {
3373 $ids[] = $user['id'];
3376 return api_format_data("ids", $type, ['id' => $ids]);
3379 /// @TODO move to top of file or somewhere better
3380 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3383 * Returns the instance's configuration information.
3385 * @param string $type Return type (atom, rss, xml, json)
3387 * @return array|string
3389 function api_statusnet_config($type)
3393 $name = Config::get('config', 'sitename');
3394 $server = $a->getHostName();
3395 $logo = System::baseUrl() . '/images/friendica-64.png';
3396 $email = Config::get('config', 'admin_email');
3397 $closed = intval(Config::get('config', 'register_policy')) === REGISTER_CLOSED ? 'true' : 'false';
3398 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3399 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3400 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3401 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3404 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3405 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3406 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3407 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3408 'shorturllength' => '30',
3410 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3411 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3412 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3413 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3418 return api_format_data('config', $type, ['config' => $config]);
3421 /// @TODO move to top of file or somewhere better
3422 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3423 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3427 * @param string $type Return type (atom, rss, xml, json)
3429 * @return array|string
3431 function api_statusnet_version($type)
3434 $fake_statusnet_version = "0.9.7";
3436 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3439 /// @TODO move to top of file or somewhere better
3440 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3441 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3445 * @param string $type Return type (atom, rss, xml, json)
3447 * @todo use api_format_data() to return data
3449 function api_ff_ids($type)
3452 throw new ForbiddenException();
3459 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3462 "SELECT `pcontact`.`id` FROM `contact`
3463 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3464 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3467 if (!DBA::isResult($r)) {
3472 foreach ($r as $rr) {
3473 if ($stringify_ids) {
3476 $ids[] = intval($rr['id']);
3480 return api_format_data("ids", $type, ['id' => $ids]);
3484 * Returns the ID of every user the user is following.
3486 * @param string $type Return type (atom, rss, xml, json)
3488 * @return array|string
3489 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3491 function api_friends_ids($type)
3493 return api_ff_ids($type);
3497 * Returns the ID of every user following the user.
3499 * @param string $type Return type (atom, rss, xml, json)
3501 * @return array|string
3502 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3504 function api_followers_ids($type)
3506 return api_ff_ids($type);
3509 /// @TODO move to top of file or somewhere better
3510 api_register_func('api/friends/ids', 'api_friends_ids', true);
3511 api_register_func('api/followers/ids', 'api_followers_ids', true);
3514 * Sends a new direct message.
3516 * @param string $type Return type (atom, rss, xml, json)
3518 * @return array|string
3519 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3521 function api_direct_messages_new($type)
3525 if (api_user() === false) {
3526 throw new ForbiddenException();
3529 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3533 $sender = api_get_user($a);
3536 if (!empty($_POST['screen_name'])) {
3538 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3540 DBA::escape($_POST['screen_name'])
3543 if (DBA::isResult($r)) {
3544 // Selecting the id by priority, friendica first
3545 api_best_nickname($r);
3547 $recipient = api_get_user($a, $r[0]['nurl']);
3550 $recipient = api_get_user($a, $_POST['user_id']);
3553 if (empty($recipient)) {
3554 throw new NotFoundException('Recipient not found');
3559 if (!empty($_REQUEST['replyto'])) {
3561 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3563 intval($_REQUEST['replyto'])
3565 $replyto = $r[0]['parent-uri'];
3566 $sub = $r[0]['title'];
3568 if (!empty($_REQUEST['title'])) {
3569 $sub = $_REQUEST['title'];
3571 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3575 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3578 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3579 $ret = api_format_messages($r[0], $recipient, $sender);
3581 $ret = ["error"=>$id];
3584 $data = ['direct_message'=>$ret];
3590 $data = api_rss_extra($a, $data, $sender);
3594 return api_format_data("direct-messages", $type, $data);
3597 /// @TODO move to top of file or somewhere better
3598 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3601 * Destroys a direct message.
3603 * @brief delete a direct_message from mail table through api
3605 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3606 * @return string|array
3607 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3609 function api_direct_messages_destroy($type)
3613 if (api_user() === false) {
3614 throw new ForbiddenException();
3618 $user_info = api_get_user($a);
3620 $id = defaults($_REQUEST, 'id', 0);
3622 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3623 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3624 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3626 $uid = $user_info['uid'];
3627 // error if no id or parenturi specified (for clients posting parent-uri as well)
3628 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3629 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3630 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3633 // BadRequestException if no id specified (for clients using Twitter API)
3635 throw new BadRequestException('Message id not specified');
3638 // add parent-uri to sql command if specified by calling app
3639 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3641 // get data of the specified message id
3643 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3648 // error message if specified id is not in database
3649 if (!DBA::isResult($r)) {
3650 if ($verbose == "true") {
3651 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3652 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3654 /// @todo BadRequestException ok for Twitter API clients?
3655 throw new BadRequestException('message id not in database');
3660 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3665 if ($verbose == "true") {
3668 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3669 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3671 $answer = ['result' => 'error', 'message' => 'unknown error'];
3672 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3675 /// @todo return JSON data like Twitter API not yet implemented
3678 /// @TODO move to top of file or somewhere better
3679 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3684 * @brief unfollow contact
3686 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3687 * @return string|array
3688 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3690 function api_friendships_destroy($type)
3695 if ($uid === false) {
3696 throw new ForbiddenException();
3699 $contact_id = defaults($_REQUEST, 'user_id');
3701 if (empty($contact_id)) {
3702 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3703 throw new BadRequestException("no user_id specified");
3706 // Get Contact by given id
3707 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3709 if(!DBA::isResult($contact)) {
3710 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3711 throw new NotFoundException("no contact found to given ID");
3714 $url = $contact["url"];
3716 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3717 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3718 Strings::normaliseLink($url), $url];
3719 $contact = DBA::selectFirst('contact', [], $condition);
3721 if (!DBA::isResult($contact)) {
3722 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3723 throw new NotFoundException("Not following Contact");
3726 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3727 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3728 throw new ExpectationFailedException("Not supported");
3731 $dissolve = ($contact['rel'] == Contact::SHARING);
3733 $owner = User::getOwnerDataById($uid);
3735 Contact::terminateFriendship($owner, $contact, $dissolve);
3738 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3739 throw new NotFoundException("Error Processing Request");
3742 // Sharing-only contacts get deleted as there no relationship any more
3744 Contact::remove($contact['id']);
3746 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3749 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3750 unset($contact["uid"]);
3751 unset($contact["self"]);
3753 // Set screen_name since Twidere requests it
3754 $contact["screen_name"] = $contact["nick"];
3756 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3758 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3762 * @param string $type Return type (atom, rss, xml, json)
3763 * @param string $box
3764 * @param string $verbose
3766 * @return array|string
3768 function api_direct_messages_box($type, $box, $verbose)
3771 if (api_user() === false) {
3772 throw new ForbiddenException();
3775 $count = defaults($_GET, 'count', 20);
3776 $page = defaults($_REQUEST, 'page', 1) - 1;
3781 $since_id = defaults($_REQUEST, 'since_id', 0);
3782 $max_id = defaults($_REQUEST, 'max_id', 0);
3784 $user_id = defaults($_REQUEST, 'user_id', '');
3785 $screen_name = defaults($_REQUEST, 'screen_name', '');
3788 unset($_REQUEST["user_id"]);
3789 unset($_GET["user_id"]);
3791 unset($_REQUEST["screen_name"]);
3792 unset($_GET["screen_name"]);
3794 $user_info = api_get_user($a);
3795 if ($user_info === false) {
3796 throw new ForbiddenException();
3798 $profile_url = $user_info["url"];
3801 $start = $page * $count;
3806 if ($box=="sentbox") {
3807 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3808 } elseif ($box == "conversation") {
3809 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
3810 } elseif ($box == "all") {
3811 $sql_extra = "true";
3812 } elseif ($box == "inbox") {
3813 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3817 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3820 if ($user_id != "") {
3821 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3822 } elseif ($screen_name !="") {
3823 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3827 "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",
3833 if ($verbose == "true" && !DBA::isResult($r)) {
3834 $answer = ['result' => 'error', 'message' => 'no mails available'];
3835 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3839 foreach ($r as $item) {
3840 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3841 $recipient = $user_info;
3842 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3843 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3844 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3845 $sender = $user_info;
3848 if (isset($recipient) && isset($sender)) {
3849 $ret[] = api_format_messages($item, $recipient, $sender);
3854 $data = ['direct_message' => $ret];
3859 $data = api_rss_extra($a, $data, $user_info);
3863 return api_format_data("direct-messages", $type, $data);
3867 * Returns the most recent direct messages sent by the user.
3869 * @param string $type Return type (atom, rss, xml, json)
3871 * @return array|string
3872 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3874 function api_direct_messages_sentbox($type)
3876 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3877 return api_direct_messages_box($type, "sentbox", $verbose);
3881 * Returns the most recent direct messages sent to the user.
3883 * @param string $type Return type (atom, rss, xml, json)
3885 * @return array|string
3886 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3888 function api_direct_messages_inbox($type)
3890 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3891 return api_direct_messages_box($type, "inbox", $verbose);
3896 * @param string $type Return type (atom, rss, xml, json)
3898 * @return array|string
3900 function api_direct_messages_all($type)
3902 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3903 return api_direct_messages_box($type, "all", $verbose);
3908 * @param string $type Return type (atom, rss, xml, json)
3910 * @return array|string
3912 function api_direct_messages_conversation($type)
3914 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3915 return api_direct_messages_box($type, "conversation", $verbose);
3918 /// @TODO move to top of file or somewhere better
3919 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3920 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3921 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3922 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3925 * Returns an OAuth Request Token.
3927 * @see https://oauth.net/core/1.0/#auth_step1
3929 function api_oauth_request_token()
3931 $oauth1 = new FKOAuth1();
3933 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3934 } catch (Exception $e) {
3935 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3943 * Returns an OAuth Access Token.
3945 * @return array|string
3946 * @see https://oauth.net/core/1.0/#auth_step3
3948 function api_oauth_access_token()
3950 $oauth1 = new FKOAuth1();
3952 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3953 } catch (Exception $e) {
3954 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3961 /// @TODO move to top of file or somewhere better
3962 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3963 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3967 * @brief delete a complete photoalbum with all containing photos from database through api
3969 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3970 * @return string|array
3972 function api_fr_photoalbum_delete($type)
3974 if (api_user() === false) {
3975 throw new ForbiddenException();
3978 $album = defaults($_REQUEST, 'album', "");
3980 // we do not allow calls without album string
3982 throw new BadRequestException("no albumname specified");
3984 // check if album is existing
3986 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3990 if (!DBA::isResult($r)) {
3991 throw new BadRequestException("album not available");
3994 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3995 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3996 foreach ($r as $rr) {
3997 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
3998 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4000 if (!DBA::isResult($photo_item)) {
4001 throw new InternalServerErrorException("problem with deleting items occured");
4003 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4006 // now let's delete all photos from the album
4007 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4009 // return success of deletion or error message
4011 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4012 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4014 throw new InternalServerErrorException("unknown error - deleting from database failed");
4019 * @brief update the name of the album for all photos of an album
4021 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4022 * @return string|array
4024 function api_fr_photoalbum_update($type)
4026 if (api_user() === false) {
4027 throw new ForbiddenException();
4030 $album = defaults($_REQUEST, 'album', "");
4031 $album_new = defaults($_REQUEST, 'album_new', "");
4033 // we do not allow calls without album string
4035 throw new BadRequestException("no albumname specified");
4037 if ($album_new == "") {
4038 throw new BadRequestException("no new albumname specified");
4040 // check if album is existing
4041 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4042 throw new BadRequestException("album not available");
4044 // now let's update all photos to the albumname
4045 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4047 // return success of updating or error message
4049 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4050 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4052 throw new InternalServerErrorException("unknown error - updating in database failed");
4058 * @brief list all photos of the authenticated user
4060 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4061 * @return string|array
4063 function api_fr_photos_list($type)
4065 if (api_user() === false) {
4066 throw new ForbiddenException();
4069 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4070 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4071 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4072 intval(local_user())
4075 'image/jpeg' => 'jpg',
4076 'image/png' => 'png',
4077 'image/gif' => 'gif'
4079 $data = ['photo'=>[]];
4080 if (DBA::isResult($r)) {
4081 foreach ($r as $rr) {
4083 $photo['id'] = $rr['resource-id'];
4084 $photo['album'] = $rr['album'];
4085 $photo['filename'] = $rr['filename'];
4086 $photo['type'] = $rr['type'];
4087 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4088 $photo['created'] = $rr['created'];
4089 $photo['edited'] = $rr['edited'];
4090 $photo['desc'] = $rr['desc'];
4092 if ($type == "xml") {
4093 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4095 $photo['thumb'] = $thumb;
4096 $data['photo'][] = $photo;
4100 return api_format_data("photos", $type, $data);
4104 * @brief upload a new photo or change an existing photo
4106 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4107 * @return string|array
4109 function api_fr_photo_create_update($type)
4111 if (api_user() === false) {
4112 throw new ForbiddenException();
4115 $photo_id = defaults($_REQUEST, 'photo_id', null);
4116 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4117 $album = defaults($_REQUEST, 'album', null);
4118 $album_new = defaults($_REQUEST, 'album_new', null);
4119 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4120 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4121 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4122 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4123 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4125 // do several checks on input parameters
4126 // we do not allow calls without album string
4127 if ($album == null) {
4128 throw new BadRequestException("no albumname specified");
4130 // if photo_id == null --> we are uploading a new photo
4131 if ($photo_id == null) {
4134 // error if no media posted in create-mode
4135 if (empty($_FILES['media'])) {
4137 throw new BadRequestException("no media data submitted");
4140 // album_new will be ignored in create-mode
4145 // check if photo is existing in databasei
4146 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4147 throw new BadRequestException("photo not available");
4151 // checks on acl strings provided by clients
4152 $acl_input_error = false;
4153 $acl_input_error |= check_acl_input($allow_cid);
4154 $acl_input_error |= check_acl_input($deny_cid);
4155 $acl_input_error |= check_acl_input($allow_gid);
4156 $acl_input_error |= check_acl_input($deny_gid);
4157 if ($acl_input_error) {
4158 throw new BadRequestException("acl data invalid");
4160 // now let's upload the new media in create-mode
4161 if ($mode == "create") {
4162 $media = $_FILES['media'];
4163 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4165 // return success of updating or error message
4166 if (!is_null($data)) {
4167 return api_format_data("photo_create", $type, $data);
4169 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4173 // now let's do the changes in update-mode
4174 if ($mode == "update") {
4175 $updated_fields = [];
4177 if (!is_null($desc)) {
4178 $updated_fields['desc'] = $desc;
4181 if (!is_null($album_new)) {
4182 $updated_fields['album'] = $album_new;
4185 if (!is_null($allow_cid)) {
4186 $allow_cid = trim($allow_cid);
4187 $updated_fields['allow_cid'] = $allow_cid;
4190 if (!is_null($deny_cid)) {
4191 $deny_cid = trim($deny_cid);
4192 $updated_fields['deny_cid'] = $deny_cid;
4195 if (!is_null($allow_gid)) {
4196 $allow_gid = trim($allow_gid);
4197 $updated_fields['allow_gid'] = $allow_gid;
4200 if (!is_null($deny_gid)) {
4201 $deny_gid = trim($deny_gid);
4202 $updated_fields['deny_gid'] = $deny_gid;
4206 if (count($updated_fields) > 0) {
4207 $nothingtodo = false;
4208 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4210 $nothingtodo = true;
4213 if (!empty($_FILES['media'])) {
4214 $nothingtodo = false;
4215 $media = $_FILES['media'];
4216 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4217 if (!is_null($data)) {
4218 return api_format_data("photo_update", $type, $data);
4222 // return success of updating or error message
4224 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4225 return api_format_data("photo_update", $type, ['$result' => $answer]);
4228 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4229 return api_format_data("photo_update", $type, ['$result' => $answer]);
4231 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4234 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4238 * @brief delete a single photo from the database through api
4240 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4241 * @return string|array
4243 function api_fr_photo_delete($type)
4245 if (api_user() === false) {
4246 throw new ForbiddenException();
4249 $photo_id = defaults($_REQUEST, 'photo_id', null);
4251 // do several checks on input parameters
4252 // we do not allow calls without photo id
4253 if ($photo_id == null) {
4254 throw new BadRequestException("no photo_id specified");
4256 // check if photo is existing in database
4257 $r = Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()]);
4259 throw new BadRequestException("photo not available");
4261 // now we can perform on the deletion of the photo
4262 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4264 // return success of deletion or error message
4266 // retrieve the id of the parent element (the photo element)
4267 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4268 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4270 if (!DBA::isResult($photo_item)) {
4271 throw new InternalServerErrorException("problem with deleting items occured");
4273 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4274 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4275 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4277 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4278 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4280 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4286 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4288 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4289 * @return string|array
4291 function api_fr_photo_detail($type)
4293 if (api_user() === false) {
4294 throw new ForbiddenException();
4296 if (empty($_REQUEST['photo_id'])) {
4297 throw new BadRequestException("No photo id.");
4300 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4301 $photo_id = $_REQUEST['photo_id'];
4303 // prepare json/xml output with data from database for the requested photo
4304 $data = prepare_photo_data($type, $scale, $photo_id);
4306 return api_format_data("photo_detail", $type, $data);
4311 * Updates the user’s profile image.
4313 * @brief updates the profile image for the user (either a specified profile or the default profile)
4315 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4317 * @return string|array
4318 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4320 function api_account_update_profile_image($type)
4322 if (api_user() === false) {
4323 throw new ForbiddenException();
4326 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4328 // error if image data is missing
4329 if (empty($_FILES['image'])) {
4330 throw new BadRequestException("no media data submitted");
4333 // check if specified profile id is valid
4334 if ($profile_id != 0) {
4335 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4336 // error message if specified profile id is not in database
4337 if (!DBA::isResult($profile)) {
4338 throw new BadRequestException("profile_id not available");
4340 $is_default_profile = $profile['is-default'];
4342 $is_default_profile = 1;
4345 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4347 if (!empty($_FILES['image'])) {
4348 $media = $_FILES['image'];
4349 } elseif (!empty($_FILES['media'])) {
4350 $media = $_FILES['media'];
4352 // save new profile image
4353 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4356 if (is_array($media['type'])) {
4357 $filetype = $media['type'][0];
4359 $filetype = $media['type'];
4361 if ($filetype == "image/jpeg") {
4363 } elseif ($filetype == "image/png") {
4366 throw new InternalServerErrorException('Unsupported filetype');
4369 // change specified profile or all profiles to the new resource-id
4370 if ($is_default_profile) {
4371 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4372 Photo::update(['profile' => false], $condition);
4374 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4375 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4376 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4379 Contact::updateSelfFromUserID(api_user(), true);
4381 // Update global directory in background
4382 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4383 if ($url && strlen(Config::get('system', 'directory'))) {
4384 Worker::add(PRIORITY_LOW, "Directory", $url);
4387 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4389 // output for client
4391 return api_account_verify_credentials($type);
4393 // SaveMediaToDatabase failed for some reason
4394 throw new InternalServerErrorException("image upload failed");
4398 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4399 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4400 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4401 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4402 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4403 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4404 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4405 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4406 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4409 * Update user profile
4411 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4413 * @return array|string
4415 function api_account_update_profile($type)
4417 $local_user = api_user();
4418 $api_user = api_get_user(get_app());
4420 if (!empty($_POST['name'])) {
4421 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4422 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4423 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4424 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4427 if (isset($_POST['description'])) {
4428 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4429 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4430 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4433 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4434 // Update global directory in background
4435 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4436 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4439 return api_account_verify_credentials($type);
4442 /// @TODO move to top of file or somewhere better
4443 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4447 * @param string $acl_string
4449 function check_acl_input($acl_string)
4451 if ($acl_string == null || $acl_string == " ") {
4454 $contact_not_found = false;
4456 // split <x><y><z> into array of cid's
4457 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4459 // check for each cid if it is available on server
4460 $cid_array = $array[0];
4461 foreach ($cid_array as $cid) {
4462 $cid = str_replace("<", "", $cid);
4463 $cid = str_replace(">", "", $cid);
4464 $condition = ['id' => $cid, 'uid' => api_user()];
4465 $contact_not_found |= !DBA::exists('contact', $condition);
4467 return $contact_not_found;
4472 * @param string $mediatype
4473 * @param array $media
4474 * @param string $type
4475 * @param string $album
4476 * @param string $allow_cid
4477 * @param string $deny_cid
4478 * @param string $allow_gid
4479 * @param string $deny_gid
4480 * @param string $desc
4481 * @param integer $profile
4482 * @param boolean $visibility
4483 * @param string $photo_id
4485 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)
4493 if (is_array($media)) {
4494 if (is_array($media['tmp_name'])) {
4495 $src = $media['tmp_name'][0];
4497 $src = $media['tmp_name'];
4499 if (is_array($media['name'])) {
4500 $filename = basename($media['name'][0]);
4502 $filename = basename($media['name']);
4504 if (is_array($media['size'])) {
4505 $filesize = intval($media['size'][0]);
4507 $filesize = intval($media['size']);
4509 if (is_array($media['type'])) {
4510 $filetype = $media['type'][0];
4512 $filetype = $media['type'];
4516 if ($filetype == "") {
4517 $filetype=Image::guessType($filename);
4519 $imagedata = @getimagesize($src);
4521 $filetype = $imagedata['mime'];
4524 "File upload src: " . $src . " - filename: " . $filename .
4525 " - size: " . $filesize . " - type: " . $filetype,
4529 // check if there was a php upload error
4530 if ($filesize == 0 && $media['error'] == 1) {
4531 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4533 // check against max upload size within Friendica instance
4534 $maximagesize = Config::get('system', 'maximagesize');
4535 if ($maximagesize && ($filesize > $maximagesize)) {
4536 $formattedBytes = Strings::formatBytes($maximagesize);
4537 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4540 // create Photo instance with the data of the image
4541 $imagedata = @file_get_contents($src);
4542 $Image = new Image($imagedata, $filetype);
4543 if (!$Image->isValid()) {
4544 throw new InternalServerErrorException("unable to process image data");
4547 // check orientation of image
4548 $Image->orient($src);
4551 // check max length of images on server
4552 $max_length = Config::get('system', 'max_image_length');
4554 $max_length = MAX_IMAGE_LENGTH;
4556 if ($max_length > 0) {
4557 $Image->scaleDown($max_length);
4558 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4560 $width = $Image->getWidth();
4561 $height = $Image->getHeight();
4563 // create a new resource-id if not already provided
4564 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4566 if ($mediatype == "photo") {
4567 // upload normal image (scales 0, 1, 2)
4568 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4570 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4572 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4574 if ($width > 640 || $height > 640) {
4575 $Image->scaleDown(640);
4576 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4578 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4582 if ($width > 320 || $height > 320) {
4583 $Image->scaleDown(320);
4584 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4586 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4589 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4590 } elseif ($mediatype == "profileimage") {
4591 // upload profile image (scales 4, 5, 6)
4592 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4594 if ($width > 300 || $height > 300) {
4595 $Image->scaleDown(300);
4596 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4598 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4602 if ($width > 80 || $height > 80) {
4603 $Image->scaleDown(80);
4604 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4606 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4610 if ($width > 48 || $height > 48) {
4611 $Image->scaleDown(48);
4612 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4614 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4617 $Image->__destruct();
4618 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4621 if (isset($r) && $r) {
4622 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4623 if ($photo_id == null && $mediatype == "photo") {
4624 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4626 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4627 return prepare_photo_data($type, false, $hash);
4629 throw new InternalServerErrorException("image upload failed");
4635 * @param string $hash
4636 * @param string $allow_cid
4637 * @param string $deny_cid
4638 * @param string $allow_gid
4639 * @param string $deny_gid
4640 * @param string $filetype
4641 * @param boolean $visibility
4643 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4645 // get data about the api authenticated user
4646 $uri = Item::newURI(intval(api_user()));
4647 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4650 $arr['guid'] = System::createUUID();
4651 $arr['uid'] = intval(api_user());
4653 $arr['parent-uri'] = $uri;
4654 $arr['type'] = 'photo';
4656 $arr['resource-id'] = $hash;
4657 $arr['contact-id'] = $owner_record['id'];
4658 $arr['owner-name'] = $owner_record['name'];
4659 $arr['owner-link'] = $owner_record['url'];
4660 $arr['owner-avatar'] = $owner_record['thumb'];
4661 $arr['author-name'] = $owner_record['name'];
4662 $arr['author-link'] = $owner_record['url'];
4663 $arr['author-avatar'] = $owner_record['thumb'];
4665 $arr['allow_cid'] = $allow_cid;
4666 $arr['allow_gid'] = $allow_gid;
4667 $arr['deny_cid'] = $deny_cid;
4668 $arr['deny_gid'] = $deny_gid;
4669 $arr['visible'] = $visibility;
4673 'image/jpeg' => 'jpg',
4674 'image/png' => 'png',
4675 'image/gif' => 'gif'
4678 // adds link to the thumbnail scale photo
4679 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4680 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4683 // do the magic for storing the item in the database and trigger the federation to other contacts
4689 * @param string $type
4691 * @param string $photo_id
4695 function prepare_photo_data($type, $scale, $photo_id)
4698 $user_info = api_get_user($a);
4700 if ($user_info === false) {
4701 throw new ForbiddenException();
4704 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4705 $data_sql = ($scale === false ? "" : "data, ");
4707 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4708 // clients needs to convert this in their way for further processing
4710 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4711 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4712 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4713 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4715 intval(local_user()),
4716 DBA::escape($photo_id),
4721 'image/jpeg' => 'jpg',
4722 'image/png' => 'png',
4723 'image/gif' => 'gif'
4726 // prepare output data for photo
4727 if (DBA::isResult($r)) {
4728 $data = ['photo' => $r[0]];
4729 $data['photo']['id'] = $data['photo']['resource-id'];
4730 if ($scale !== false) {
4731 $data['photo']['data'] = base64_encode($data['photo']['data']);
4733 unset($data['photo']['datasize']); //needed only with scale param
4735 if ($type == "xml") {
4736 $data['photo']['links'] = [];
4737 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4738 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4740 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4743 $data['photo']['link'] = [];
4744 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4746 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4747 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4751 unset($data['photo']['resource-id']);
4752 unset($data['photo']['minscale']);
4753 unset($data['photo']['maxscale']);
4755 throw new NotFoundException();
4758 // retrieve item element for getting activities (like, dislike etc.) related to photo
4759 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4760 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4762 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4764 // retrieve comments on photo
4765 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4766 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4768 $statuses = Item::selectForUser(api_user(), [], $condition);
4770 // prepare output of comments
4771 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4773 if ($type == "xml") {
4775 foreach ($commentData as $comment) {
4776 $comments[$k++ . ":comment"] = $comment;
4779 foreach ($commentData as $comment) {
4780 $comments[] = $comment;
4783 $data['photo']['friendica_comments'] = $comments;
4785 // include info if rights on photo and rights on item are mismatching
4786 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4787 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4788 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4789 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4790 $data['photo']['rights_mismatch'] = $rights_mismatch;
4797 * Similar as /mod/redir.php
4798 * redirect to 'url' after dfrn auth
4800 * Why this when there is mod/redir.php already?
4801 * This use api_user() and api_login()
4804 * c_url: url of remote contact to auth to
4805 * url: string, url to redirect after auth
4807 function api_friendica_remoteauth()
4809 $url = defaults($_GET, 'url', '');
4810 $c_url = defaults($_GET, 'c_url', '');
4812 if ($url === '' || $c_url === '') {
4813 throw new BadRequestException("Wrong parameters.");
4816 $c_url = Strings::normaliseLink($c_url);
4820 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4822 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
4823 throw new BadRequestException("Unknown contact");
4826 $cid = $contact['id'];
4828 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4830 if ($contact['duplex'] && $contact['issued-id']) {
4831 $orig_id = $contact['issued-id'];
4832 $dfrn_id = '1:' . $orig_id;
4834 if ($contact['duplex'] && $contact['dfrn-id']) {
4835 $orig_id = $contact['dfrn-id'];
4836 $dfrn_id = '0:' . $orig_id;
4839 $sec = Strings::getRandomHex();
4841 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4842 'sec' => $sec, 'expire' => time() + 45];
4843 DBA::insert('profile_check', $fields);
4846 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
4847 $dest = ($url ? '&destination_url=' . $url : '');
4849 System::externalRedirect(
4850 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4851 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4852 . '&type=profile&sec=' . $sec . $dest
4855 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4858 * @brief Return the item shared, if the item contains only the [share] tag
4860 * @param array $item Sharer item
4861 * @return array|false Shared item or false if not a reshare
4863 function api_share_as_retweet(&$item)
4865 $body = trim($item["body"]);
4867 if (Diaspora::isReshare($body, false) === false) {
4868 if ($item['author-id'] == $item['owner-id']) {
4871 // Reshares from OStatus, ActivityPub and Twitter
4872 $reshared_item = $item;
4873 $reshared_item['owner-id'] = $reshared_item['author-id'];
4874 $reshared_item['owner-link'] = $reshared_item['author-link'];
4875 $reshared_item['owner-name'] = $reshared_item['author-name'];
4876 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
4877 return $reshared_item;
4881 /// @TODO "$1" should maybe mean '$1' ?
4882 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4884 * Skip if there is no shared message in there
4885 * we already checked this in diaspora::isReshare()
4886 * but better one more than one less...
4888 if (($body == $attributes) || empty($attributes)) {
4892 // build the fake reshared item
4893 $reshared_item = $item;
4896 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4897 if (!empty($matches[1])) {
4898 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4901 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4902 if (!empty($matches[1])) {
4903 $author = $matches[1];
4907 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4908 if (!empty($matches[1])) {
4909 $profile = $matches[1];
4912 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4913 if (!empty($matches[1])) {
4914 $profile = $matches[1];
4918 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4919 if (!empty($matches[1])) {
4920 $avatar = $matches[1];
4923 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4924 if (!empty($matches[1])) {
4925 $avatar = $matches[1];
4929 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4930 if (!empty($matches[1])) {
4931 $link = $matches[1];
4934 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4935 if (!empty($matches[1])) {
4936 $link = $matches[1];
4940 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4941 if (!empty($matches[1])) {
4942 $posted = $matches[1];
4945 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4946 if (!empty($matches[1])) {
4947 $posted = $matches[1];
4950 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4952 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4956 $reshared_item["body"] = $shared_body;
4957 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
4958 $reshared_item["author-name"] = $author;
4959 $reshared_item["author-link"] = $profile;
4960 $reshared_item["author-avatar"] = $avatar;
4961 $reshared_item["plink"] = $link;
4962 $reshared_item["created"] = $posted;
4963 $reshared_item["edited"] = $posted;
4965 return $reshared_item;
4970 * @param string $profile
4972 * @return string|false
4973 * @todo remove trailing junk from profile url
4974 * @todo pump.io check has to check the website
4976 function api_get_nick($profile)
4981 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4982 DBA::escape(Strings::normaliseLink($profile))
4985 if (DBA::isResult($r)) {
4986 $nick = $r[0]["nick"];
4991 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4992 DBA::escape(Strings::normaliseLink($profile))
4995 if (DBA::isResult($r)) {
4996 $nick = $r[0]["nick"];
5001 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5002 if ($friendica != $profile) {
5008 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5009 if ($diaspora != $profile) {
5015 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5016 if ($twitter != $profile) {
5023 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5024 if ($StatusnetHost != $profile) {
5025 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5026 if ($StatusnetUser != $profile) {
5027 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5028 $user = json_decode($UserData);
5030 $nick = $user->screen_name;
5036 // To-Do: look at the page if its really a pumpio site
5037 //if (!$nick == "") {
5038 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5039 // if ($pumpio != $profile)
5041 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5054 * @param array $item
5058 function api_in_reply_to($item)
5062 $in_reply_to['status_id'] = null;
5063 $in_reply_to['user_id'] = null;
5064 $in_reply_to['status_id_str'] = null;
5065 $in_reply_to['user_id_str'] = null;
5066 $in_reply_to['screen_name'] = null;
5068 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5069 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5070 if (DBA::isResult($parent)) {
5071 $in_reply_to['status_id'] = intval($parent['id']);
5073 $in_reply_to['status_id'] = intval($item['parent']);
5076 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5078 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5079 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5081 if (DBA::isResult($parent)) {
5082 if ($parent['author-nick'] == "") {
5083 $parent['author-nick'] = api_get_nick($parent['author-link']);
5086 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5087 $in_reply_to['user_id'] = intval($parent['author-id']);
5088 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5091 // There seems to be situation, where both fields are identical:
5092 // https://github.com/friendica/friendica/issues/1010
5093 // This is a bugfix for that.
5094 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5096 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']]);
5097 $in_reply_to['status_id'] = null;
5098 $in_reply_to['user_id'] = null;
5099 $in_reply_to['status_id_str'] = null;
5100 $in_reply_to['user_id_str'] = null;
5101 $in_reply_to['screen_name'] = null;
5105 return $in_reply_to;
5110 * @param string $text
5114 function api_clean_plain_items($text)
5116 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5118 $text = BBCode::cleanPictureLinks($text);
5119 $URLSearchString = "^\[\]";
5121 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5123 if ($include_entities == "true") {
5124 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5127 // Simplify "attachment" element
5128 $text = api_clean_attachments($text);
5134 * @brief Removes most sharing information for API text export
5136 * @param string $body The original body
5138 * @return string Cleaned body
5140 function api_clean_attachments($body)
5142 $data = BBCode::getAttachmentData($body);
5149 if (isset($data["text"])) {
5150 $body = $data["text"];
5152 if (($body == "") && isset($data["title"])) {
5153 $body = $data["title"];
5155 if (isset($data["url"])) {
5156 $body .= "\n".$data["url"];
5158 $body .= $data["after"];
5165 * @param array $contacts
5169 function api_best_nickname(&$contacts)
5173 if (count($contacts) == 0) {
5177 foreach ($contacts as $contact) {
5178 if ($contact["network"] == "") {
5179 $contact["network"] = "dfrn";
5180 $best_contact = [$contact];
5184 if (sizeof($best_contact) == 0) {
5185 foreach ($contacts as $contact) {
5186 if ($contact["network"] == "dfrn") {
5187 $best_contact = [$contact];
5192 if (sizeof($best_contact) == 0) {
5193 foreach ($contacts as $contact) {
5194 if ($contact["network"] == "dspr") {
5195 $best_contact = [$contact];
5200 if (sizeof($best_contact) == 0) {
5201 foreach ($contacts as $contact) {
5202 if ($contact["network"] == "stat") {
5203 $best_contact = [$contact];
5208 if (sizeof($best_contact) == 0) {
5209 foreach ($contacts as $contact) {
5210 if ($contact["network"] == "pump") {
5211 $best_contact = [$contact];
5216 if (sizeof($best_contact) == 0) {
5217 foreach ($contacts as $contact) {
5218 if ($contact["network"] == "twit") {
5219 $best_contact = [$contact];
5224 if (sizeof($best_contact) == 1) {
5225 $contacts = $best_contact;
5227 $contacts = [$contacts[0]];
5232 * Return all or a specified group of the user with the containing contacts.
5234 * @param string $type Return type (atom, rss, xml, json)
5236 * @return array|string
5238 function api_friendica_group_show($type)
5242 if (api_user() === false) {
5243 throw new ForbiddenException();
5247 $user_info = api_get_user($a);
5248 $gid = defaults($_REQUEST, 'gid', 0);
5249 $uid = $user_info['uid'];
5251 // get data of the specified group id or all groups if not specified
5254 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5258 // error message if specified gid is not in database
5259 if (!DBA::isResult($r)) {
5260 throw new BadRequestException("gid not available");
5264 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5269 // loop through all groups and retrieve all members for adding data in the user array
5271 foreach ($r as $rr) {
5272 $members = Contact::getByGroupId($rr['id']);
5275 if ($type == "xml") {
5276 $user_element = "users";
5278 foreach ($members as $member) {
5279 $user = api_get_user($a, $member['nurl']);
5280 $users[$k++.":user"] = $user;
5283 $user_element = "user";
5284 foreach ($members as $member) {
5285 $user = api_get_user($a, $member['nurl']);
5289 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5291 return api_format_data("groups", $type, ['group' => $grps]);
5293 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5297 * Delete the specified group of the user.
5299 * @param string $type Return type (atom, rss, xml, json)
5301 * @return array|string
5303 function api_friendica_group_delete($type)
5307 if (api_user() === false) {
5308 throw new ForbiddenException();
5312 $user_info = api_get_user($a);
5313 $gid = defaults($_REQUEST, 'gid', 0);
5314 $name = defaults($_REQUEST, 'name', "");
5315 $uid = $user_info['uid'];
5317 // error if no gid specified
5318 if ($gid == 0 || $name == "") {
5319 throw new BadRequestException('gid or name not specified');
5322 // get data of the specified group id
5324 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5328 // error message if specified gid is not in database
5329 if (!DBA::isResult($r)) {
5330 throw new BadRequestException('gid not available');
5333 // get data of the specified group id and group name
5335 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5340 // error message if specified gid is not in database
5341 if (!DBA::isResult($rname)) {
5342 throw new BadRequestException('wrong group name');
5346 $ret = Group::removeByName($uid, $name);
5349 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5350 return api_format_data("group_delete", $type, ['result' => $success]);
5352 throw new BadRequestException('other API error');
5355 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5360 * @param string $type Return type (atom, rss, xml, json)
5362 * @return array|string
5363 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5365 function api_lists_destroy($type)
5369 if (api_user() === false) {
5370 throw new ForbiddenException();
5374 $user_info = api_get_user($a);
5375 $gid = defaults($_REQUEST, 'list_id', 0);
5376 $uid = $user_info['uid'];
5378 // error if no gid specified
5380 throw new BadRequestException('gid not specified');
5383 // get data of the specified group id
5384 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5385 // error message if specified gid is not in database
5387 throw new BadRequestException('gid not available');
5390 if (Group::remove($gid)) {
5392 'name' => $group['name'],
5393 'id' => intval($gid),
5394 'id_str' => (string) $gid,
5395 'user' => $user_info
5398 return api_format_data("lists", $type, ['lists' => $list]);
5401 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5404 * Add a new group to the database.
5406 * @param string $name Group name
5407 * @param int $uid User ID
5408 * @param array $users List of users to add to the group
5412 function group_create($name, $uid, $users = [])
5414 // error if no name specified
5416 throw new BadRequestException('group name not specified');
5419 // get data of the specified group name
5421 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5425 // error message if specified group name already exists
5426 if (DBA::isResult($rname)) {
5427 throw new BadRequestException('group name already exists');
5430 // check if specified group name is a deleted group
5432 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5436 // error message if specified group name already exists
5437 if (DBA::isResult($rname)) {
5438 $reactivate_group = true;
5442 $ret = Group::create($uid, $name);
5444 $gid = Group::getIdByName($uid, $name);
5446 throw new BadRequestException('other API error');
5450 $erroraddinguser = false;
5452 foreach ($users as $user) {
5453 $cid = $user['cid'];
5454 // check if user really exists as contact
5456 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5460 if (count($contact)) {
5461 Group::addMember($gid, $cid);
5463 $erroraddinguser = true;
5464 $errorusers[] = $cid;
5468 // return success message incl. missing users in array
5469 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5471 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5475 * Create the specified group with the posted array of contacts.
5477 * @param string $type Return type (atom, rss, xml, json)
5479 * @return array|string
5481 function api_friendica_group_create($type)
5485 if (api_user() === false) {
5486 throw new ForbiddenException();
5490 $user_info = api_get_user($a);
5491 $name = defaults($_REQUEST, 'name', "");
5492 $uid = $user_info['uid'];
5493 $json = json_decode($_POST['json'], true);
5494 $users = $json['user'];
5496 $success = group_create($name, $uid, $users);
5498 return api_format_data("group_create", $type, ['result' => $success]);
5500 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5503 * Create a new group.
5505 * @param string $type Return type (atom, rss, xml, json)
5507 * @return array|string
5508 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5510 function api_lists_create($type)
5514 if (api_user() === false) {
5515 throw new ForbiddenException();
5519 $user_info = api_get_user($a);
5520 $name = defaults($_REQUEST, 'name', "");
5521 $uid = $user_info['uid'];
5523 $success = group_create($name, $uid);
5524 if ($success['success']) {
5526 'name' => $success['name'],
5527 'id' => intval($success['gid']),
5528 'id_str' => (string) $success['gid'],
5529 'user' => $user_info
5532 return api_format_data("lists", $type, ['lists'=>$grp]);
5535 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5538 * Update the specified group with the posted array of contacts.
5540 * @param string $type Return type (atom, rss, xml, json)
5542 * @return array|string
5544 function api_friendica_group_update($type)
5548 if (api_user() === false) {
5549 throw new ForbiddenException();
5553 $user_info = api_get_user($a);
5554 $uid = $user_info['uid'];
5555 $gid = defaults($_REQUEST, 'gid', 0);
5556 $name = defaults($_REQUEST, 'name', "");
5557 $json = json_decode($_POST['json'], true);
5558 $users = $json['user'];
5560 // error if no name specified
5562 throw new BadRequestException('group name not specified');
5565 // error if no gid specified
5567 throw new BadRequestException('gid not specified');
5571 $members = Contact::getByGroupId($gid);
5572 foreach ($members as $member) {
5573 $cid = $member['id'];
5574 foreach ($users as $user) {
5575 $found = ($user['cid'] == $cid ? true : false);
5577 if (!isset($found) || !$found) {
5578 Group::removeMemberByName($uid, $name, $cid);
5583 $erroraddinguser = false;
5585 foreach ($users as $user) {
5586 $cid = $user['cid'];
5587 // check if user really exists as contact
5589 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5594 if (count($contact)) {
5595 Group::addMember($gid, $cid);
5597 $erroraddinguser = true;
5598 $errorusers[] = $cid;
5602 // return success message incl. missing users in array
5603 $status = ($erroraddinguser ? "missing user" : "ok");
5604 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5605 return api_format_data("group_update", $type, ['result' => $success]);
5608 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5611 * Update information about a group.
5613 * @param string $type Return type (atom, rss, xml, json)
5615 * @return array|string
5616 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5618 function api_lists_update($type)
5622 if (api_user() === false) {
5623 throw new ForbiddenException();
5627 $user_info = api_get_user($a);
5628 $gid = defaults($_REQUEST, 'list_id', 0);
5629 $name = defaults($_REQUEST, 'name', "");
5630 $uid = $user_info['uid'];
5632 // error if no gid specified
5634 throw new BadRequestException('gid not specified');
5637 // get data of the specified group id
5638 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5639 // error message if specified gid is not in database
5641 throw new BadRequestException('gid not available');
5644 if (Group::update($gid, $name)) {
5647 'id' => intval($gid),
5648 'id_str' => (string) $gid,
5649 'user' => $user_info
5652 return api_format_data("lists", $type, ['lists' => $list]);
5656 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5660 * @param string $type Return type (atom, rss, xml, json)
5662 * @return array|string
5664 function api_friendica_activity($type)
5668 if (api_user() === false) {
5669 throw new ForbiddenException();
5671 $verb = strtolower($a->argv[3]);
5672 $verb = preg_replace("|\..*$|", "", $verb);
5674 $id = defaults($_REQUEST, 'id', 0);
5676 $res = Item::performLike($id, $verb);
5679 if ($type == "xml") {
5684 return api_format_data('ok', $type, ['ok' => $ok]);
5686 throw new BadRequestException('Error adding activity');
5690 /// @TODO move to top of file or somewhere better
5691 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5692 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5693 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5694 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5695 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5696 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5697 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5698 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5699 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5700 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5703 * @brief Returns notifications
5705 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5706 * @return string|array
5708 function api_friendica_notification($type)
5712 if (api_user() === false) {
5713 throw new ForbiddenException();
5716 throw new BadRequestException("Invalid argument count");
5718 $nm = new NotificationsManager();
5720 $notes = $nm->getAll([], "+seen -date", 50);
5722 if ($type == "xml") {
5724 if (!empty($notes)) {
5725 foreach ($notes as $note) {
5726 $xmlnotes[] = ["@attributes" => $note];
5732 return api_format_data("notes", $type, ['note' => $notes]);
5736 * POST request with 'id' param as notification id
5738 * @brief Set notification as seen and returns associated item (if possible)
5740 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5741 * @return string|array
5743 function api_friendica_notification_seen($type)
5746 $user_info = api_get_user($a);
5748 if (api_user() === false || $user_info === false) {
5749 throw new ForbiddenException();
5752 throw new BadRequestException("Invalid argument count");
5755 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5757 $nm = new NotificationsManager();
5758 $note = $nm->getByID($id);
5759 if (is_null($note)) {
5760 throw new BadRequestException("Invalid argument");
5763 $nm->setSeen($note);
5764 if ($note['otype']=='item') {
5765 // would be really better with an ItemsManager and $im->getByID() :-P
5766 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5767 if (DBA::isResult($item)) {
5768 // we found the item, return it to the user
5769 $ret = api_format_items([$item], $user_info, false, $type);
5770 $data = ['status' => $ret];
5771 return api_format_data("status", $type, $data);
5773 // the item can't be found, but we set the note as seen, so we count this as a success
5775 return api_format_data('result', $type, ['result' => "success"]);
5778 /// @TODO move to top of file or somewhere better
5779 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5780 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5783 * @brief update a direct_message to seen state
5785 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5786 * @return string|array (success result=ok, error result=error with error message)
5788 function api_friendica_direct_messages_setseen($type)
5791 if (api_user() === false) {
5792 throw new ForbiddenException();
5796 $user_info = api_get_user($a);
5797 $uid = $user_info['uid'];
5798 $id = defaults($_REQUEST, 'id', 0);
5800 // return error if id is zero
5802 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5803 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5806 // error message if specified id is not in database
5807 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5808 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5809 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5812 // update seen indicator
5813 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5817 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5818 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5820 $answer = ['result' => 'error', 'message' => 'unknown error'];
5821 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5825 /// @TODO move to top of file or somewhere better
5826 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5829 * @brief search for direct_messages containing a searchstring through api
5831 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5832 * @param string $box
5833 * @return string|array (success: success=true if found and search_result contains found messages,
5834 * success=false if nothing was found, search_result='nothing found',
5835 * error: result=error with error message)
5837 function api_friendica_direct_messages_search($type, $box = "")
5841 if (api_user() === false) {
5842 throw new ForbiddenException();
5846 $user_info = api_get_user($a);
5847 $searchstring = defaults($_REQUEST, 'searchstring', "");
5848 $uid = $user_info['uid'];
5850 // error if no searchstring specified
5851 if ($searchstring == "") {
5852 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5853 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5856 // get data for the specified searchstring
5858 "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",
5860 DBA::escape('%'.$searchstring.'%')
5863 $profile_url = $user_info["url"];
5865 // message if nothing was found
5866 if (!DBA::isResult($r)) {
5867 $success = ['success' => false, 'search_results' => 'problem with query'];
5868 } elseif (count($r) == 0) {
5869 $success = ['success' => false, 'search_results' => 'nothing found'];
5872 foreach ($r as $item) {
5873 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5874 $recipient = $user_info;
5875 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5876 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5877 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5878 $sender = $user_info;
5881 if (isset($recipient) && isset($sender)) {
5882 $ret[] = api_format_messages($item, $recipient, $sender);
5885 $success = ['success' => true, 'search_results' => $ret];
5888 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5891 /// @TODO move to top of file or somewhere better
5892 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5895 * @brief return data of all the profiles a user has to the client
5897 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5898 * @return string|array
5900 function api_friendica_profile_show($type)
5904 if (api_user() === false) {
5905 throw new ForbiddenException();
5909 $profile_id = defaults($_REQUEST, 'profile_id', 0);
5911 // retrieve general information about profiles for user
5912 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5913 $directory = Config::get('system', 'directory');
5915 // get data of the specified profile id or all profiles of the user if not specified
5916 if ($profile_id != 0) {
5918 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5923 // error message if specified gid is not in database
5924 if (!DBA::isResult($r)) {
5925 throw new BadRequestException("profile_id not available");
5929 "SELECT * FROM `profile` WHERE `uid` = %d",
5933 // loop through all returned profiles and retrieve data and users
5936 foreach ($r as $rr) {
5937 $profile = api_format_items_profiles($rr);
5939 // select all users from contact table, loop and prepare standard return for user data
5942 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5947 foreach ($nurls as $nurl) {
5948 $user = api_get_user($a, $nurl['nurl']);
5949 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5951 $profile['users'] = $users;
5953 // add prepared profile data to array for final return
5954 if ($type == "xml") {
5955 $profiles[$k++ . ":profile"] = $profile;
5957 $profiles[] = $profile;
5961 // return settings, authenticated user and profiles data
5962 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
5964 $result = ['multi_profiles' => $multi_profiles ? true : false,
5965 'global_dir' => $directory,
5966 'friendica_owner' => api_get_user($a, $self['nurl']),
5967 'profiles' => $profiles];
5968 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5970 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5973 * Returns a list of saved searches.
5975 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5977 * @param string $type Return format: json or xml
5979 * @return string|array
5981 function api_saved_searches_list($type)
5983 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5986 while ($term = $terms->fetch()) {
5988 'created_at' => api_date(time()),
5989 'id' => intval($term['id']),
5990 'id_str' => $term['id'],
5991 'name' => $term['term'],
5993 'query' => $term['term']
5999 return api_format_data("terms", $type, ['terms' => $result]);
6002 /// @TODO move to top of file or somewhere better
6003 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6006 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6008 * @brief Number of comments
6010 * @param object $data [Status, Status]
6014 function bindComments(&$data)
6016 if (count($data) == 0) {
6022 foreach ($data as $item) {
6023 $ids[] = $item['id'];
6026 $idStr = DBA::escape(implode(', ', $ids));
6027 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6028 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6029 $itemsData = DBA::toArray($items);
6031 foreach ($itemsData as $item) {
6032 $comments[$item['parent']] = $item['comments'];
6035 foreach ($data as $idx => $item) {
6037 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6042 @TODO Maybe open to implement?
6044 [pagename] => api/1.1/statuses/lookup.json
6045 [id] => 605138389168451584
6046 [include_cards] => true
6047 [cards_platform] => Android-12
6048 [include_entities] => true
6049 [include_my_retweet] => 1
6051 [include_reply_count] => true
6052 [include_descendent_reply_count] => true
6056 Not implemented by now:
6057 statuses/retweets_of_me
6062 account/update_location
6063 account/update_profile_background_image
6066 friendica/profile/update
6067 friendica/profile/create
6068 friendica/profile/delete
6070 Not implemented in status.net:
6071 statuses/retweeted_to_me
6072 statuses/retweeted_by_me
6073 direct_messages/destroy
6075 account/update_delivery_device
6076 notifications/follow