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\Addon;
15 use Friendica\Core\Config;
16 use Friendica\Core\L10n;
17 use Friendica\Core\NotificationsManager;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
21 use Friendica\Database\DBM;
22 use Friendica\Model\Contact;
23 use Friendica\Model\Group;
24 use Friendica\Model\Item;
25 use Friendica\Model\Mail;
26 use Friendica\Model\Photo;
27 use Friendica\Model\User;
28 use Friendica\Network\FKOAuth1;
29 use Friendica\Network\HTTPException;
30 use Friendica\Network\HTTPException\BadRequestException;
31 use Friendica\Network\HTTPException\ForbiddenException;
32 use Friendica\Network\HTTPException\InternalServerErrorException;
33 use Friendica\Network\HTTPException\MethodNotAllowedException;
34 use Friendica\Network\HTTPException\NotFoundException;
35 use Friendica\Network\HTTPException\NotImplementedException;
36 use Friendica\Network\HTTPException\TooManyRequestsException;
37 use Friendica\Network\HTTPException\UnauthorizedException;
38 use Friendica\Object\Image;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Network;
42 use Friendica\Util\XML;
44 require_once 'include/conversation.php';
45 require_once 'mod/share.php';
46 require_once 'mod/item.php';
47 require_once 'include/security.php';
48 require_once 'mod/wall_upload.php';
49 require_once 'mod/proxy.php';
51 define('API_METHOD_ANY', '*');
52 define('API_METHOD_GET', 'GET');
53 define('API_METHOD_POST', 'POST,PUT');
54 define('API_METHOD_DELETE', 'POST,DELETE');
60 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
61 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
62 * into a page, and visitors will post something without noticing it).
64 * @brief Auth API user
68 if (x($_SESSION, 'allow_api')) {
76 * Clients can send 'source' parameter to be show in post metadata
77 * as "sent via <source>".
78 * Some clients doesn't send a source param, we support ones we know
81 * @brief Get source name from API client
84 * Client source name, default to "api" if unset/unknown
88 if (requestdata('source')) {
89 return requestdata('source');
92 // Support for known clients that doesn't send a source name
93 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
97 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
103 * @brief Format date for API
105 * @param string $str Source date, as UTC
106 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
108 function api_date($str)
110 // Wed May 23 06:01:13 +0000 2007
111 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
115 * Register a function to be the endpoint for defined API path.
117 * @brief Register API endpoint
119 * @param string $path API URL path, relative to System::baseUrl()
120 * @param string $func Function name to call on path request
121 * @param bool $auth API need logged user
122 * @param string $method HTTP method reqiured to call this endpoint.
123 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
124 * Default to API_METHOD_ANY
126 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
136 // Workaround for hotot
137 $path = str_replace("api/", "api/1.1/", $path);
147 * Log in user via OAuth1 or Simple HTTP Auth.
148 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
150 * @brief Login API user
152 * @param object $a App
153 * @hook 'authenticate'
155 * 'username' => username from login form
156 * 'password' => password from login form
157 * 'authenticated' => return status,
158 * 'user_record' => return authenticated user record
160 * array $user logged user record
162 function api_login(App $a)
164 $oauth1 = new FKOAuth1();
167 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
168 if (!is_null($token)) {
169 $oauth1->loginUser($token->uid);
170 Addon::callHooks('logged_in', $a->user);
173 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
174 var_dump($consumer, $token);
176 } catch (Exception $e) {
180 // workaround for HTTP-auth in CGI mode
181 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
182 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
183 if (strlen($userpass)) {
184 list($name, $password) = explode(':', $userpass);
185 $_SERVER['PHP_AUTH_USER'] = $name;
186 $_SERVER['PHP_AUTH_PW'] = $password;
190 if (!x($_SERVER, 'PHP_AUTH_USER')) {
191 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
192 header('WWW-Authenticate: Basic realm="Friendica"');
193 throw new UnauthorizedException("This API requires login");
196 $user = $_SERVER['PHP_AUTH_USER'];
197 $password = $_SERVER['PHP_AUTH_PW'];
199 // allow "user@server" login (but ignore 'server' part)
200 $at = strstr($user, "@", true);
205 // next code from mod/auth.php. needs better solution
209 'username' => trim($user),
210 'password' => trim($password),
211 'authenticated' => 0,
212 'user_record' => null,
216 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
217 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
218 * and later addons should not interfere with an earlier one that succeeded.
220 Addon::callHooks('authenticate', $addon_auth);
222 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
223 $record = $addon_auth['user_record'];
225 $user_id = User::authenticate(trim($user), trim($password));
226 if ($user_id !== false) {
227 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
231 if (!DBM::is_result($record)) {
232 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
233 header('WWW-Authenticate: Basic realm="Friendica"');
234 //header('HTTP/1.0 401 Unauthorized');
235 //die('This api requires login');
236 throw new UnauthorizedException("This API requires login");
239 authenticate_success($record);
241 $_SESSION["allow_api"] = true;
243 Addon::callHooks('logged_in', $a->user);
247 * API endpoints can define which HTTP method to accept when called.
248 * This function check the current HTTP method agains endpoint
251 * @brief Check HTTP method of called API
253 * @param string $method Required methods, uppercase, separated by comma
256 function api_check_method($method)
258 if ($method == "*") {
261 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
265 * Authenticate user, call registered API function, set HTTP headers
267 * @brief Main API entry point
269 * @param object $a App
270 * @return string|array API call result
272 function api_call(App $a)
274 global $API, $called_api;
277 if (strpos($a->query_string, ".xml") > 0) {
280 if (strpos($a->query_string, ".json") > 0) {
283 if (strpos($a->query_string, ".rss") > 0) {
286 if (strpos($a->query_string, ".atom") > 0) {
291 foreach ($API as $p => $info) {
292 if (strpos($a->query_string, $p) === 0) {
293 if (!api_check_method($info['method'])) {
294 throw new MethodNotAllowedException();
297 $called_api = explode("/", $p);
298 //unset($_SERVER['PHP_AUTH_USER']);
300 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
301 if ($info['auth'] === true && api_user() === false) {
305 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
306 logger('API parameters: ' . print_r($_REQUEST, true));
308 $stamp = microtime(true);
309 $return = call_user_func($info['func'], $type);
310 $duration = (float) (microtime(true) - $stamp);
311 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
313 if (Config::get("system", "profiler")) {
314 $duration = microtime(true)-$a->performance["start"];
316 /// @TODO round() really everywhere?
318 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
319 "Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
320 round($a->performance["database"] - $a->performance["database_write"], 3),
321 round($a->performance["database_write"], 3),
322 round($a->performance["cache"], 3),
323 round($a->performance["cache_write"], 3),
324 round($a->performance["network"], 2),
325 round($a->performance["file"], 2),
326 round($duration - ($a->performance["database"]
327 + $a->performance["cache"] + $a->performance["cache_write"]
328 + $a->performance["network"] + $a->performance["file"]), 2),
334 if (Config::get("rendertime", "callstack")) {
335 $o = "Database Read:\n";
336 foreach ($a->callstack["database"] as $func => $time) {
337 $time = round($time, 3);
339 $o .= $func . ": " . $time . "\n";
342 $o .= "\nDatabase Write:\n";
343 foreach ($a->callstack["database_write"] as $func => $time) {
344 $time = round($time, 3);
346 $o .= $func . ": " . $time . "\n";
350 $o = "Cache Read:\n";
351 foreach ($a->callstack["cache"] as $func => $time) {
352 $time = round($time, 3);
354 $o .= $func . ": " . $time . "\n";
357 $o .= "\nCache Write:\n";
358 foreach ($a->callstack["cache_write"] as $func => $time) {
359 $time = round($time, 3);
361 $o .= $func . ": " . $time . "\n";
365 $o .= "\nNetwork:\n";
366 foreach ($a->callstack["network"] as $func => $time) {
367 $time = round($time, 3);
369 $o .= $func . ": " . $time . "\n";
372 logger($o, LOGGER_DEBUG);
376 if (false === $return) {
378 * api function returned false withour throw an
379 * exception. This should not happend, throw a 500
381 throw new InternalServerErrorException();
386 header("Content-Type: text/xml");
389 header("Content-Type: application/json");
390 $json = json_encode(end($return));
391 if (x($_GET, 'callback')) {
392 $json = $_GET['callback'] . "(" . $json . ")";
397 header("Content-Type: application/rss+xml");
398 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
401 header("Content-Type: application/atom+xml");
402 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
409 logger('API call not implemented: ' . $a->query_string);
410 throw new NotImplementedException();
411 } catch (HTTPException $e) {
412 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
413 return api_error($type, $e);
418 * @brief Format API error string
420 * @param string $type Return type (xml, json, rss, as)
421 * @param object $e HTTPException Error object
422 * @return string|array error message formatted as $type
424 function api_error($type, $e)
428 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
429 /// @TODO: https://dev.twitter.com/overview/api/response-codes
431 $error = ["error" => $error,
432 "code" => $e->httpcode . " " . $e->httpdesc,
433 "request" => $a->query_string];
435 $return = api_format_data('status', $type, ['status' => $error]);
439 header("Content-Type: text/xml");
442 header("Content-Type: application/json");
443 $return = json_encode($return);
446 header("Content-Type: application/rss+xml");
449 header("Content-Type: application/atom+xml");
457 * @brief Set values for RSS template
460 * @param array $arr Array to be passed to template
461 * @param array $user_info User info
463 * @todo find proper type-hints
465 function api_rss_extra(App $a, $arr, $user_info)
467 if (is_null($user_info)) {
468 $user_info = api_get_user($a);
471 $arr['$user'] = $user_info;
473 'alternate' => $user_info['url'],
474 'self' => System::baseUrl() . "/" . $a->query_string,
475 'base' => System::baseUrl(),
476 'updated' => api_date(null),
477 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
478 'language' => $user_info['language'],
479 'logo' => System::baseUrl() . "/images/friendica-32.png",
487 * @brief Unique contact to contact url.
489 * @param int $id Contact id
490 * @return bool|string
491 * Contact url or False if contact id is unknown
493 function api_unique_id_to_nurl($id)
495 $r = dba::selectFirst('contact', ['nurl'], ['id' => $id]);
497 if (DBM::is_result($r)) {
505 * @brief Get user info array.
507 * @param object $a App
508 * @param int|string $contact_id Contact ID or URL
510 function api_get_user(App $a, $contact_id = null)
518 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
520 // Searching for contact URL
521 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
522 $user = dbesc(normalise_link($contact_id));
524 $extra_query = "AND `contact`.`nurl` = '%s' ";
525 if (api_user() !== false) {
526 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
530 // Searching for contact id with uid = 0
531 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
532 $user = dbesc(api_unique_id_to_nurl(intval($contact_id)));
535 throw new BadRequestException("User ID ".$contact_id." not found.");
539 $extra_query = "AND `contact`.`nurl` = '%s' ";
540 if (api_user() !== false) {
541 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
545 if (is_null($user) && x($_GET, 'user_id')) {
546 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
549 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
553 $extra_query = "AND `contact`.`nurl` = '%s' ";
554 if (api_user() !== false) {
555 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
558 if (is_null($user) && x($_GET, 'screen_name')) {
559 $user = dbesc($_GET['screen_name']);
560 $extra_query = "AND `contact`.`nick` = '%s' ";
561 if (api_user() !== false) {
562 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
566 if (is_null($user) && x($_GET, 'profileurl')) {
567 $user = dbesc(normalise_link($_GET['profileurl']));
568 $extra_query = "AND `contact`.`nurl` = '%s' ";
569 if (api_user() !== false) {
570 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
574 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
575 $argid = count($called_api);
576 list($user, $null) = explode(".", $a->argv[$argid]);
577 if (is_numeric($user)) {
578 $user = dbesc(api_unique_id_to_nurl(intval($user)));
582 $extra_query = "AND `contact`.`nurl` = '%s' ";
583 if (api_user() !== false) {
584 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
588 $user = dbesc($user);
589 $extra_query = "AND `contact`.`nick` = '%s' ";
590 if (api_user() !== false) {
591 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
596 logger("api_get_user: user ".$user, LOGGER_DEBUG);
599 if (api_user() === false) {
603 $user = $_SESSION['uid'];
604 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
608 logger('api_user: ' . $extra_query . ', user: ' . $user);
612 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
618 // Selecting the id by priority, friendica first
619 if (is_array($uinfo)) {
620 api_best_nickname($uinfo);
623 // if the contact wasn't found, fetch it from the contacts with uid = 0
624 if (!DBM::is_result($uinfo)) {
628 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
631 if (DBM::is_result($r)) {
632 $network_name = ContactSelector::networkToName($r[0]['network'], $r[0]['url']);
634 // If no nick where given, extract it from the address
635 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
636 $r[0]['nick'] = api_get_nick($r[0]["url"]);
641 'id_str' => (string) $r[0]["id"],
642 'name' => $r[0]["name"],
643 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
644 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
645 'description' => $r[0]["about"],
646 'profile_image_url' => $r[0]["micro"],
647 'profile_image_url_https' => $r[0]["micro"],
648 'profile_image_url_profile_size' => $r[0]["thumb"],
649 'profile_image_url_large' => $r[0]["photo"],
650 'url' => $r[0]["url"],
651 'protected' => false,
652 'followers_count' => 0,
653 'friends_count' => 0,
655 'created_at' => api_date($r[0]["created"]),
656 'favourites_count' => 0,
658 'time_zone' => 'UTC',
659 'geo_enabled' => false,
661 'statuses_count' => 0,
663 'contributors_enabled' => false,
664 'is_translator' => false,
665 'is_translation_enabled' => false,
666 'following' => false,
667 'follow_request_sent' => false,
668 'statusnet_blocking' => false,
669 'notifications' => false,
670 'statusnet_profile_url' => $r[0]["url"],
672 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
673 'pid' => Contact::getIdForURL($r[0]["url"], 0, true),
675 'network' => $r[0]["network"],
680 throw new BadRequestException("User ".$url." not found.");
684 if ($uinfo[0]['self']) {
685 if ($uinfo[0]['network'] == "") {
686 $uinfo[0]['network'] = NETWORK_DFRN;
690 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
694 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
698 /// @TODO old-lost code? (twice)
699 // Counting is deactivated by now, due to performance issues
700 // count public wall messages
701 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
702 // intval($uinfo[0]['uid'])
704 //$countitms = $r[0]['count'];
707 // Counting is deactivated by now, due to performance issues
708 //$r = q("SELECT count(*) as `count` FROM `item`
709 // WHERE `contact-id` = %d",
710 // intval($uinfo[0]['id'])
712 //$countitms = $r[0]['count'];
716 /// @TODO old-lost code? (twice)
718 // Counting is deactivated by now, due to performance issues
720 $r = q("SELECT count(*) as `count` FROM `contact`
721 WHERE `uid` = %d AND `rel` IN ( %d, %d )
722 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
723 intval($uinfo[0]['uid']),
724 intval(CONTACT_IS_SHARING),
725 intval(CONTACT_IS_FRIEND)
727 $countfriends = $r[0]['count'];
729 $r = q("SELECT count(*) as `count` FROM `contact`
730 WHERE `uid` = %d AND `rel` IN ( %d, %d )
731 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
732 intval($uinfo[0]['uid']),
733 intval(CONTACT_IS_FOLLOWER),
734 intval(CONTACT_IS_FRIEND)
736 $countfollowers = $r[0]['count'];
738 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
739 intval($uinfo[0]['uid'])
741 $starred = $r[0]['count'];
744 if (! $uinfo[0]['self']) {
754 // Add a nick if it isn't present there
755 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
756 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
759 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
761 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
763 if (!empty($profile[0]['about'])) {
764 $description = $profile[0]['about'];
766 $description = $uinfo[0]["about"];
769 if (!empty($usr[0]['default-location'])) {
770 $location = $usr[0]['default-location'];
771 } elseif (!empty($uinfo[0]["location"])) {
772 $location = $uinfo[0]["location"];
774 $location = $network_name;
778 'id' => intval($pcontact_id),
779 'id_str' => (string) intval($pcontact_id),
780 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
781 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
782 'location' => $location,
783 'description' => $description,
784 'profile_image_url' => $uinfo[0]['micro'],
785 'profile_image_url_https' => $uinfo[0]['micro'],
786 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
787 'profile_image_url_large' => $uinfo[0]["photo"],
788 'url' => $uinfo[0]['url'],
789 'protected' => false,
790 'followers_count' => intval($countfollowers),
791 'friends_count' => intval($countfriends),
793 'created_at' => api_date($uinfo[0]['created']),
794 'favourites_count' => intval($starred),
796 'time_zone' => 'UTC',
797 'geo_enabled' => false,
799 'statuses_count' => intval($countitms),
801 'contributors_enabled' => false,
802 'is_translator' => false,
803 'is_translation_enabled' => false,
804 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
805 'follow_request_sent' => false,
806 'statusnet_blocking' => false,
807 'notifications' => false,
809 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
810 'statusnet_profile_url' => $uinfo[0]['url'],
811 'uid' => intval($uinfo[0]['uid']),
812 'cid' => intval($uinfo[0]['cid']),
813 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
814 'self' => $uinfo[0]['self'],
815 'network' => $uinfo[0]['network'],
818 // If this is a local user and it uses Frio, we can get its color preferences.
820 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
821 if ($theme_info['theme'] === 'frio') {
822 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
823 if ($schema && ($schema != '---')) {
824 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
825 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
826 require_once $schemefile;
829 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
830 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
831 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
837 $link_color = "#6fdbe8";
840 $bgcolor = "#ededed";
843 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
844 $ret['profile_link_color'] = str_replace('#', '', $link_color);
845 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
853 * @brief return api-formatted array for item's author and owner
855 * @param object $a App
856 * @param array $item item from db
857 * @return array(array:author, array:owner)
859 function api_item_get_user(App $a, $item)
861 $status_user = api_get_user($a, $item["author-id"]);
863 $status_user["protected"] = $item["private"];
865 if ($item['thr-parent'] == $item['uri']) {
866 $owner_user = api_get_user($a, $item["owner-id"]);
868 $owner_user = $status_user;
871 return ([$status_user, $owner_user]);
875 * @brief walks recursively through an array with the possibility to change value and key
877 * @param array $array The array to walk through
878 * @param string $callback The callback function
880 * @return array the transformed array
882 function api_walk_recursive(array &$array, callable $callback)
886 foreach ($array as $k => $v) {
888 if ($callback($v, $k)) {
889 $new_array[$k] = api_walk_recursive($v, $callback);
892 if ($callback($v, $k)) {
903 * @brief Callback function to transform the array in an array that can be transformed in a XML file
905 * @param mixed $item Array item value
906 * @param string $key Array key
908 * @return boolean Should the array item be deleted?
910 function api_reformat_xml(&$item, &$key)
912 if (is_bool($item)) {
913 $item = ($item ? "true" : "false");
916 if (substr($key, 0, 10) == "statusnet_") {
917 $key = "statusnet:".substr($key, 10);
918 } elseif (substr($key, 0, 10) == "friendica_") {
919 $key = "friendica:".substr($key, 10);
921 /// @TODO old-lost code?
923 // $key = "default:".$key;
929 * @brief Creates the XML from a JSON style array
931 * @param array $data JSON style array
932 * @param string $root_element Name of the root element
934 * @return string The XML data
936 function api_create_xml(array $data, $root_element)
938 $childname = key($data);
939 $data2 = array_pop($data);
942 $namespaces = ["" => "http://api.twitter.com",
943 "statusnet" => "http://status.net/schema/api/1/",
944 "friendica" => "http://friendi.ca/schema/api/1/",
945 "georss" => "http://www.georss.org/georss"];
947 /// @todo Auto detection of needed namespaces
948 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
952 if (is_array($data2)) {
953 api_walk_recursive($data2, "api_reformat_xml");
960 foreach ($data2 as $item) {
961 $data4[$i++ . ":" . $childname] = $item;
967 $data3 = [$root_element => $data2];
969 $ret = XML::fromArray($data3, $xml, false, $namespaces);
974 * @brief Formats the data according to the data type
976 * @param string $root_element Name of the root element
977 * @param string $type Return type (atom, rss, xml, json)
978 * @param array $data JSON style array
980 * @return (string|array) XML data or JSON data
982 function api_format_data($root_element, $type, $data)
988 $ret = api_create_xml($data, $root_element);
1004 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
1005 * returns a 401 status code and an error message if not.
1006 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
1008 * @param string $type Return type (atom, rss, xml, json)
1010 function api_account_verify_credentials($type)
1015 if (api_user() === false) {
1016 throw new ForbiddenException();
1019 unset($_REQUEST["user_id"]);
1020 unset($_GET["user_id"]);
1022 unset($_REQUEST["screen_name"]);
1023 unset($_GET["screen_name"]);
1025 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1027 $user_info = api_get_user($a);
1029 // "verified" isn't used here in the standard
1030 unset($user_info["verified"]);
1032 // - Adding last status
1033 if (!$skip_status) {
1034 $user_info["status"] = api_status_show("raw");
1035 if (!count($user_info["status"])) {
1036 unset($user_info["status"]);
1038 unset($user_info["status"]["user"]);
1042 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1043 unset($user_info["uid"]);
1044 unset($user_info["self"]);
1046 return api_format_data("user", $type, ['user' => $user_info]);
1049 /// @TODO move to top of file or somewhere better
1050 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1053 * Get data from $_POST or $_GET
1057 function requestdata($k)
1059 if (x($_POST, $k)) {
1069 * Deprecated function to upload media.
1071 * @param string $type Return type (atom, rss, xml, json)
1073 * @return array|string
1075 function api_statuses_mediap($type)
1079 if (api_user() === false) {
1080 logger('api_statuses_update: no user');
1081 throw new ForbiddenException();
1083 $user_info = api_get_user($a);
1085 $_REQUEST['type'] = 'wall';
1086 $_REQUEST['profile_uid'] = api_user();
1087 $_REQUEST['api_source'] = true;
1088 $txt = requestdata('status');
1089 /// @TODO old-lost code?
1090 //$txt = urldecode(requestdata('status'));
1092 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1093 $txt = html2bb_video($txt);
1094 $config = HTMLPurifier_Config::createDefault();
1095 $config->set('Cache.DefinitionImpl', null);
1096 $purifier = new HTMLPurifier($config);
1097 $txt = $purifier->purify($txt);
1099 $txt = HTML::toBBCode($txt);
1101 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1103 $picture = wall_upload_post($a, false);
1105 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1106 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1109 // this should output the last post (the one we just posted).
1110 return api_status_show($type);
1113 /// @TODO move this to top of file or somewhere better!
1114 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1117 * Updates the user’s current status.
1119 * @param string $type Return type (atom, rss, xml, json)
1121 * @return array|string
1122 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1124 function api_statuses_update($type)
1129 if (api_user() === false) {
1130 logger('api_statuses_update: no user');
1131 throw new ForbiddenException();
1136 // convert $_POST array items to the form we use for web posts.
1137 if (requestdata('htmlstatus')) {
1138 $txt = requestdata('htmlstatus');
1139 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1140 $txt = html2bb_video($txt);
1142 $config = HTMLPurifier_Config::createDefault();
1143 $config->set('Cache.DefinitionImpl', null);
1145 $purifier = new HTMLPurifier($config);
1146 $txt = $purifier->purify($txt);
1148 $_REQUEST['body'] = HTML::toBBCode($txt);
1151 $_REQUEST['body'] = requestdata('status');
1154 $_REQUEST['title'] = requestdata('title');
1156 $parent = requestdata('in_reply_to_status_id');
1158 // Twidere sends "-1" if it is no reply ...
1159 if ($parent == -1) {
1163 if (ctype_digit($parent)) {
1164 $_REQUEST['parent'] = $parent;
1166 $_REQUEST['parent_uri'] = $parent;
1169 if (requestdata('lat') && requestdata('long')) {
1170 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1172 $_REQUEST['profile_uid'] = api_user();
1175 $_REQUEST['type'] = 'net-comment';
1177 // Check for throttling (maximum posts per day, week and month)
1178 $throttle_day = Config::get('system', 'throttle_limit_day');
1179 if ($throttle_day > 0) {
1180 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1183 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1184 AND `created` > '%s' AND `id` = `parent`",
1189 if (DBM::is_result($r)) {
1190 $posts_day = $r[0]["posts_day"];
1195 if ($posts_day > $throttle_day) {
1196 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1197 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1198 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));
1202 $throttle_week = Config::get('system', 'throttle_limit_week');
1203 if ($throttle_week > 0) {
1204 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1207 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1208 AND `created` > '%s' AND `id` = `parent`",
1213 if (DBM::is_result($r)) {
1214 $posts_week = $r[0]["posts_week"];
1219 if ($posts_week > $throttle_week) {
1220 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1221 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1222 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));
1226 $throttle_month = Config::get('system', 'throttle_limit_month');
1227 if ($throttle_month > 0) {
1228 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1231 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1232 AND `created` > '%s' AND `id` = `parent`",
1237 if (DBM::is_result($r)) {
1238 $posts_month = $r[0]["posts_month"];
1243 if ($posts_month > $throttle_month) {
1244 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1245 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1246 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));
1250 $_REQUEST['type'] = 'wall';
1253 if (x($_FILES, 'media')) {
1254 // upload the image if we have one
1255 $picture = wall_upload_post($a, false);
1256 if (is_array($media)) {
1257 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1261 // To-Do: Multiple IDs
1262 if (requestdata('media_ids')) {
1264 "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",
1265 intval(requestdata('media_ids')),
1268 if (DBM::is_result($r)) {
1269 $phototypes = Image::supportedTypes();
1270 $ext = $phototypes[$r[0]['type']];
1271 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1272 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1276 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1278 $_REQUEST['api_source'] = true;
1280 if (!x($_REQUEST, "source")) {
1281 $_REQUEST["source"] = api_source();
1284 // call out normal post function
1287 // this should output the last post (the one we just posted).
1288 return api_status_show($type);
1291 /// @TODO move to top of file or somewhere better
1292 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1293 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1296 * Uploads an image to Friendica.
1299 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1301 function api_media_upload()
1305 if (api_user() === false) {
1307 throw new ForbiddenException();
1312 if (!x($_FILES, 'media')) {
1314 throw new BadRequestException("No media.");
1317 $media = wall_upload_post($a, false);
1320 throw new InternalServerErrorException();
1324 $returndata["media_id"] = $media["id"];
1325 $returndata["media_id_string"] = (string)$media["id"];
1326 $returndata["size"] = $media["size"];
1327 $returndata["image"] = ["w" => $media["width"],
1328 "h" => $media["height"],
1329 "image_type" => $media["type"]];
1331 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1333 return ["media" => $returndata];
1336 /// @TODO move to top of file or somewhere better
1337 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1341 * @param string $type Return type (atom, rss, xml, json)
1343 * @return array|string
1345 function api_status_show($type)
1349 $user_info = api_get_user($a);
1351 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1353 if ($type == "raw") {
1354 $privacy_sql = "AND NOT `private`";
1359 // get last public wall message
1360 $condition = ["`owner-id` = ? AND `uid` = ? AND `type` != 'activity' ".$privacy_sql,
1361 $user_info['pid'], api_user()];
1362 $lastwall = dba::selectFirst('item', [], $condition, ['order' => ['id' => true]]);
1364 if (DBM::is_result($lastwall)) {
1365 $in_reply_to = api_in_reply_to($lastwall);
1367 $converted = api_convert_item($lastwall);
1369 if ($type == "xml") {
1370 $geo = "georss:point";
1376 'created_at' => api_date($lastwall['created']),
1377 'id' => intval($lastwall['id']),
1378 'id_str' => (string) $lastwall['id'],
1379 'text' => $converted["text"],
1380 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1381 'truncated' => false,
1382 'in_reply_to_status_id' => $in_reply_to['status_id'],
1383 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1384 'in_reply_to_user_id' => $in_reply_to['user_id'],
1385 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1386 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1387 'user' => $user_info,
1389 'coordinates' => "",
1391 'contributors' => "",
1392 'is_quote_status' => false,
1393 'retweet_count' => 0,
1394 'favorite_count' => 0,
1395 'favorited' => $lastwall['starred'] ? true : false,
1396 'retweeted' => false,
1397 'possibly_sensitive' => false,
1399 'statusnet_html' => $converted["html"],
1400 'statusnet_conversation_id' => $lastwall['parent'],
1401 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1404 if (count($converted["attachments"]) > 0) {
1405 $status_info["attachments"] = $converted["attachments"];
1408 if (count($converted["entities"]) > 0) {
1409 $status_info["entities"] = $converted["entities"];
1412 if ($status_info["source"] == 'web') {
1413 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
1414 } elseif (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $status_info["source"]) {
1415 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $user_info['url']).')');
1418 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1419 unset($status_info["user"]["uid"]);
1420 unset($status_info["user"]["self"]);
1422 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1424 if ($type == "raw") {
1425 return $status_info;
1428 return api_format_data("statuses", $type, ['status' => $status_info]);
1433 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1434 * The author's most recent status will be returned inline.
1436 * @param string $type Return type (atom, rss, xml, json)
1437 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1439 function api_users_show($type)
1443 $user_info = api_get_user($a);
1445 $condition = ["`owner-id` = ? AND `uid` = ? AND `verb` = ? AND `type` != 'activity' AND NOT `private`",
1446 $user_info['pid'], api_user(), ACTIVITY_POST];
1447 $lastwall = dba::selectFirst('item', [], $condition, ['order' => ['id' => true]]);
1449 if (DBM::is_result($lastwall)) {
1450 $in_reply_to = api_in_reply_to($lastwall);
1452 $converted = api_convert_item($lastwall);
1454 if ($type == "xml") {
1455 $geo = "georss:point";
1460 $user_info['status'] = [
1461 'text' => $converted["text"],
1462 'truncated' => false,
1463 'created_at' => api_date($lastwall['created']),
1464 'in_reply_to_status_id' => $in_reply_to['status_id'],
1465 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1466 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1467 'id' => intval($lastwall['contact-id']),
1468 'id_str' => (string) $lastwall['contact-id'],
1469 'in_reply_to_user_id' => $in_reply_to['user_id'],
1470 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1471 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1473 'favorited' => $lastwall['starred'] ? true : false,
1474 'statusnet_html' => $converted["html"],
1475 'statusnet_conversation_id' => $lastwall['parent'],
1476 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1479 if (count($converted["attachments"]) > 0) {
1480 $user_info["status"]["attachments"] = $converted["attachments"];
1483 if (count($converted["entities"]) > 0) {
1484 $user_info["status"]["entities"] = $converted["entities"];
1487 if ($user_info["status"]["source"] == 'web') {
1488 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
1491 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1492 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $user_info['url']) . ')');
1496 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1497 unset($user_info["uid"]);
1498 unset($user_info["self"]);
1500 return api_format_data("user", $type, ['user' => $user_info]);
1503 /// @TODO move to top of file or somewhere better
1504 api_register_func('api/users/show', 'api_users_show');
1505 api_register_func('api/externalprofile/show', 'api_users_show');
1508 * Search a public user account.
1510 * @param string $type Return type (atom, rss, xml, json)
1512 * @return array|string
1513 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1515 function api_users_search($type)
1521 if (x($_GET, 'q')) {
1522 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1524 if (!DBM::is_result($r)) {
1525 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1528 if (DBM::is_result($r)) {
1530 foreach ($r as $user) {
1531 $user_info = api_get_user($a, $user["id"]);
1533 if ($type == "xml") {
1534 $userlist[$k++.":user"] = $user_info;
1536 $userlist[] = $user_info;
1539 $userlist = ["users" => $userlist];
1541 throw new BadRequestException("User ".$_GET["q"]." not found.");
1544 throw new BadRequestException("No user specified.");
1547 return api_format_data("users", $type, $userlist);
1550 /// @TODO move to top of file or somewhere better
1551 api_register_func('api/users/search', 'api_users_search');
1554 * Return user objects
1556 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1558 * @param string $type Return format: json or xml
1560 * @return array|string
1561 * @throws NotFoundException if the results are empty.
1563 function api_users_lookup($type)
1567 if (x($_REQUEST['user_id'])) {
1568 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1570 $users[] = api_get_user(get_app(), $id);
1575 if (empty($users)) {
1576 throw new NotFoundException;
1579 return api_format_data("users", $type, ['users' => $users]);
1582 /// @TODO move to top of file or somewhere better
1583 api_register_func('api/users/lookup', 'api_users_lookup', true);
1586 * Returns statuses that match a specified query.
1588 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1590 * @param string $type Return format: json, xml, atom, rss
1592 * @return array|string
1593 * @throws BadRequestException if the "q" parameter is missing.
1595 function api_search($type)
1598 $user_info = api_get_user($a);
1600 if (api_user() === false || $user_info === false) {
1601 throw new ForbiddenException();
1607 if (!x($_REQUEST, 'q')) {
1608 throw new BadRequestException("q parameter is required.");
1611 if (x($_REQUEST, 'rpp')) {
1612 $count = $_REQUEST['rpp'];
1613 } elseif (x($_REQUEST, 'count')) {
1614 $count = $_REQUEST['count'];
1619 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1620 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1621 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1623 $start = $page * $count;
1626 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1630 "SELECT ".item_fieldlists()."
1631 FROM `item` ".item_joins(api_user())."
1632 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1633 AND `item`.`body` LIKE CONCAT('%',?,'%')
1636 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1642 $data['status'] = api_format_items(dba::inArray($r), $user_info);
1644 return api_format_data("statuses", $type, $data);
1647 /// @TODO move to top of file or somewhere better
1648 api_register_func('api/search/tweets', 'api_search', true);
1649 api_register_func('api/search', 'api_search', true);
1652 * Returns the most recent statuses posted by the user and the users they follow.
1654 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1656 * @param string $type Return type (atom, rss, xml, json)
1658 * @todo Optional parameters
1659 * @todo Add reply info
1661 function api_statuses_home_timeline($type)
1664 $user_info = api_get_user($a);
1666 if (api_user() === false || $user_info === false) {
1667 throw new ForbiddenException();
1670 unset($_REQUEST["user_id"]);
1671 unset($_GET["user_id"]);
1673 unset($_REQUEST["screen_name"]);
1674 unset($_GET["screen_name"]);
1676 // get last network messages
1679 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1680 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1684 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1685 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1686 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1687 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1688 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1690 $start = $page * $count;
1694 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1696 if ($exclude_replies > 0) {
1697 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1699 if ($conversation_id > 0) {
1700 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1703 $r = q("SELECT `item`.* FROM `item`
1704 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1705 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1706 WHERE `item`.`uid` = %d AND `verb` = '%s'
1707 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1709 AND `item`.`id` > %d
1710 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1712 dbesc(ACTIVITY_POST),
1718 $ret = api_format_items($r, $user_info, false, $type);
1720 // Set all posts from the query above to seen
1722 foreach ($r as $item) {
1723 $idarray[] = intval($item["id"]);
1726 if (!empty($idarray)) {
1727 $unseen = dba::exists('item', ['unseen' => true, 'id' => $idarray]);
1729 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1733 $data = ['status' => $ret];
1737 $data = api_rss_extra($a, $data, $user_info);
1741 return api_format_data("statuses", $type, $data);
1744 /// @TODO move to top of file or somewhere better
1745 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1746 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1749 * Returns the most recent statuses from public users.
1751 * @param string $type Return type (atom, rss, xml, json)
1753 * @return array|string
1755 function api_statuses_public_timeline($type)
1758 $user_info = api_get_user($a);
1760 if (api_user() === false || $user_info === false) {
1761 throw new ForbiddenException();
1764 // get last network messages
1767 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1768 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1772 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1773 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1774 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1775 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1776 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1778 $start = $page * $count;
1781 if ($exclude_replies && !$conversation_id) {
1783 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1787 "SELECT " . item_fieldlists() . "
1789 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1790 " . item_joins(api_user()) . "
1791 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1792 AND NOT `user`.`hidewall`
1794 AND NOT `thread`.`private`
1796 AND `thread`.`visible`
1797 AND NOT `thread`.`deleted`
1798 AND NOT `thread`.`moderated`
1799 AND `thread`.`iid` > ?
1801 ORDER BY `thread`.`iid` DESC
1802 LIMIT " . intval($start) . ", " . intval($count),
1807 $r = dba::inArray($r);
1810 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1812 if ($conversation_id > 0) {
1813 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1817 "SELECT " . item_fieldlists() . "
1819 " . item_joins(api_user()) . "
1820 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1821 AND NOT `user`.`hidewall`
1823 AND NOT `item`.`private`
1825 AND `item`.`visible`
1826 AND NOT `item`.`deleted`
1827 AND NOT `item`.`moderated`
1830 ORDER BY `item`.`id` DESC
1831 LIMIT " . intval($start) . ", " . intval($count),
1836 $r = dba::inArray($r);
1839 $ret = api_format_items($r, $user_info, false, $type);
1841 $data = ['status' => $ret];
1845 $data = api_rss_extra($a, $data, $user_info);
1849 return api_format_data("statuses", $type, $data);
1852 /// @TODO move to top of file or somewhere better
1853 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1856 * Returns the most recent statuses posted by users this node knows about.
1858 * @brief Returns the list of public federated posts this node knows about
1860 * @param string $type Return format: json, xml, atom, rss
1861 * @return array|string
1862 * @throws ForbiddenException
1864 function api_statuses_networkpublic_timeline($type)
1867 $user_info = api_get_user($a);
1869 if (api_user() === false || $user_info === false) {
1870 throw new ForbiddenException();
1873 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1874 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1877 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1878 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1882 $start = ($page - 1) * $count;
1886 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1890 "SELECT " . item_fieldlists() . "
1892 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1893 " . item_joins(api_user()) . "
1894 WHERE `thread`.`uid` = 0
1896 AND NOT `thread`.`private`
1897 AND `thread`.`visible`
1898 AND NOT `thread`.`deleted`
1899 AND NOT `thread`.`moderated`
1900 AND `thread`.`iid` > ?
1902 ORDER BY `thread`.`iid` DESC
1903 LIMIT " . intval($start) . ", " . intval($count),
1908 $r = dba::inArray($r);
1910 $ret = api_format_items($r, $user_info, false, $type);
1912 $data = ['status' => $ret];
1916 $data = api_rss_extra($a, $data, $user_info);
1920 return api_format_data("statuses", $type, $data);
1923 /// @TODO move to top of file or somewhere better
1924 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1927 * Returns a single status.
1929 * @param string $type Return type (atom, rss, xml, json)
1931 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1933 function api_statuses_show($type)
1936 $user_info = api_get_user($a);
1938 if (api_user() === false || $user_info === false) {
1939 throw new ForbiddenException();
1943 $id = intval($a->argv[3]);
1946 $id = intval($_REQUEST["id"]);
1951 $id = intval($a->argv[4]);
1954 logger('API: api_statuses_show: ' . $id);
1956 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1959 if ($conversation) {
1960 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1962 $sql_extra .= " AND `item`.`id` = %d";
1965 // try to fetch the item for the local user - or the public item, if there is no local one
1966 $uri_item = dba::selectFirst('item', ['uri'], ['id' => $id]);
1967 if (!DBM::is_result($uri_item)) {
1968 throw new BadRequestException("There is no status with this id.");
1971 $item = dba::selectFirst('item', ['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1972 if (!DBM::is_result($item)) {
1973 throw new BadRequestException("There is no status with this id.");
1979 "SELECT `item`.* FROM `item`
1980 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1981 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1982 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1983 AND `item`.`uid` IN (0, %d) AND `item`.`verb` = '%s'
1986 dbesc(ACTIVITY_POST),
1990 /// @TODO How about copying this to above methods which don't check $r ?
1991 if (!DBM::is_result($r)) {
1992 throw new BadRequestException("There is no status with this id.");
1995 $ret = api_format_items($r, $user_info, false, $type);
1997 if ($conversation) {
1998 $data = ['status' => $ret];
1999 return api_format_data("statuses", $type, $data);
2001 $data = ['status' => $ret[0]];
2002 return api_format_data("status", $type, $data);
2006 /// @TODO move to top of file or somewhere better
2007 api_register_func('api/statuses/show', 'api_statuses_show', true);
2011 * @param string $type Return type (atom, rss, xml, json)
2013 * @todo nothing to say?
2015 function api_conversation_show($type)
2018 $user_info = api_get_user($a);
2020 if (api_user() === false || $user_info === false) {
2021 throw new ForbiddenException();
2025 $id = intval($a->argv[3]);
2026 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2027 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
2031 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2032 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2034 $start = $page*$count;
2037 $id = intval($_REQUEST["id"]);
2042 $id = intval($a->argv[4]);
2045 logger('API: api_conversation_show: '.$id);
2047 // try to fetch the item for the local user - or the public item, if there is no local one
2048 $item = dba::selectFirst('item', ['parent-uri'], ['id' => $id]);
2049 if (!DBM::is_result($item)) {
2050 throw new BadRequestException("There is no status with this id.");
2053 $parent = dba::selectFirst('item', ['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
2054 if (!DBM::is_result($parent)) {
2055 throw new BadRequestException("There is no status with this id.");
2058 $id = $parent['id'];
2063 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2066 $r = q("SELECT `item`.* FROM `item`
2067 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2068 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2069 WHERE `item`.`parent` = %d AND `item`.`visible`
2070 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2071 AND `item`.`uid` IN (0, %d) AND `item`.`verb` = '%s'
2072 AND `item`.`id`>%d $sql_extra
2073 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2076 dbesc(ACTIVITY_POST),
2082 if (!DBM::is_result($r)) {
2083 throw new BadRequestException("There is no status with this id.");
2086 $ret = api_format_items($r, $user_info, false, $type);
2088 $data = ['status' => $ret];
2089 return api_format_data("statuses", $type, $data);
2092 /// @TODO move to top of file or somewhere better
2093 api_register_func('api/conversation/show', 'api_conversation_show', true);
2094 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2099 * @param string $type Return type (atom, rss, xml, json)
2101 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2103 function api_statuses_repeat($type)
2109 if (api_user() === false) {
2110 throw new ForbiddenException();
2116 $id = intval($a->argv[3]);
2119 $id = intval($_REQUEST["id"]);
2124 $id = intval($a->argv[4]);
2127 logger('API: api_statuses_repeat: '.$id);
2129 $r = q("SELECT `item`.* FROM `item`
2130 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2131 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2132 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2133 AND NOT `item`.`private`
2134 AND `item`.`id`=%d",
2138 /// @TODO other style than above functions!
2139 if (DBM::is_result($r) && $r[0]['body'] != "") {
2140 if (strpos($r[0]['body'], "[/share]") !== false) {
2141 $pos = strpos($r[0]['body'], "[share");
2142 $post = substr($r[0]['body'], $pos);
2144 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2146 $post .= $r[0]['body'];
2147 $post .= "[/share]";
2149 $_REQUEST['body'] = $post;
2150 $_REQUEST['profile_uid'] = api_user();
2151 $_REQUEST['type'] = 'wall';
2152 $_REQUEST['api_source'] = true;
2154 if (!x($_REQUEST, "source")) {
2155 $_REQUEST["source"] = api_source();
2160 throw new ForbiddenException();
2163 // this should output the last post (the one we just posted).
2165 return api_status_show($type);
2168 /// @TODO move to top of file or somewhere better
2169 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2172 * Destroys a specific status.
2174 * @param string $type Return type (atom, rss, xml, json)
2176 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2178 function api_statuses_destroy($type)
2182 if (api_user() === false) {
2183 throw new ForbiddenException();
2189 $id = intval($a->argv[3]);
2192 $id = intval($_REQUEST["id"]);
2197 $id = intval($a->argv[4]);
2200 logger('API: api_statuses_destroy: '.$id);
2202 $ret = api_statuses_show($type);
2204 Item::deleteForUser(['id' => $id], api_user());
2209 /// @TODO move to top of file or somewhere better
2210 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2213 * Returns the most recent mentions.
2215 * @param string $type Return type (atom, rss, xml, json)
2217 * @see http://developer.twitter.com/doc/get/statuses/mentions
2219 function api_statuses_mentions($type)
2222 $user_info = api_get_user($a);
2224 if (api_user() === false || $user_info === false) {
2225 throw new ForbiddenException();
2228 unset($_REQUEST["user_id"]);
2229 unset($_GET["user_id"]);
2231 unset($_REQUEST["screen_name"]);
2232 unset($_GET["screen_name"]);
2234 // get last network messages
2237 $since_id = defaults($_REQUEST, 'since_id', 0);
2238 $max_id = defaults($_REQUEST, 'max_id' , 0);
2239 $count = defaults($_REQUEST, 'count' , 20);
2240 $page = defaults($_REQUEST, 'page' , 1);
2245 $start = ($page - 1) * $count;
2250 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2253 $r = q("SELECT `item`.* FROM `item` FORCE INDEX (`uid_id`)
2254 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2255 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2256 WHERE `item`.`uid` = %d AND `item`.`verb` = '%s'
2257 AND `item`.`author-id` != %d
2258 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2259 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND NOT `ignored`)
2261 AND `item`.`id` > %d
2262 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2264 dbesc(ACTIVITY_POST),
2265 intval($user_info['pid']),
2272 $ret = api_format_items($r, $user_info, false, $type);
2274 $data = ['status' => $ret];
2278 $data = api_rss_extra($a, $data, $user_info);
2282 return api_format_data("statuses", $type, $data);
2285 /// @TODO move to top of file or somewhere better
2286 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2287 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2290 * Returns the most recent statuses posted by the user.
2292 * @brief Returns a user's public timeline
2294 * @param string $type Either "json" or "xml"
2295 * @return string|array
2296 * @throws ForbiddenException
2297 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2299 function api_statuses_user_timeline($type)
2302 $user_info = api_get_user($a);
2304 if (api_user() === false || $user_info === false) {
2305 throw new ForbiddenException();
2309 "api_statuses_user_timeline: api_user: ". api_user() .
2310 "\nuser_info: ".print_r($user_info, true) .
2311 "\n_REQUEST: ".print_r($_REQUEST, true),
2315 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2316 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2317 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2318 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2321 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2322 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2326 $start = ($page - 1) * $count;
2329 if ($user_info['self'] == 1) {
2330 $sql_extra .= " AND `item`.`wall` = 1 ";
2333 if ($exclude_replies > 0) {
2334 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2337 if ($conversation_id > 0) {
2338 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2342 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2345 $r = q("SELECT `item`.* FROM `item` FORCE INDEX (`uid_contactid_id`)
2346 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2347 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2348 WHERE `item`.`uid` = %d AND `verb` = '%s'
2349 AND `item`.`contact-id` = %d
2350 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2352 AND `item`.`id` > %d
2353 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2355 dbesc(ACTIVITY_POST),
2356 intval($user_info['cid']),
2362 $ret = api_format_items($r, $user_info, true, $type);
2364 $data = ['status' => $ret];
2368 $data = api_rss_extra($a, $data, $user_info);
2372 return api_format_data("statuses", $type, $data);
2375 /// @TODO move to top of file or somewhere better
2376 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2379 * Star/unstar an item.
2380 * param: id : id of the item
2382 * @param string $type Return type (atom, rss, xml, json)
2384 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2386 function api_favorites_create_destroy($type)
2390 if (api_user() === false) {
2391 throw new ForbiddenException();
2394 // for versioned api.
2395 /// @TODO We need a better global soluton
2396 $action_argv_id = 2;
2397 if ($a->argv[1] == "1.1") {
2398 $action_argv_id = 3;
2401 if ($a->argc <= $action_argv_id) {
2402 throw new BadRequestException("Invalid request.");
2404 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2405 if ($a->argc == $action_argv_id + 2) {
2406 $itemid = intval($a->argv[$action_argv_id + 1]);
2408 /// @TODO use x() to check if _REQUEST contains 'id'
2409 $itemid = intval($_REQUEST['id']);
2412 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2414 if (!DBM::is_result($item) || count($item) == 0) {
2415 throw new BadRequestException("Invalid item.");
2420 $item[0]['starred'] = 1;
2423 $item[0]['starred'] = 0;
2426 throw new BadRequestException("Invalid action ".$action);
2429 $r = Item::update(['starred' => $item[0]['starred']], ['id' => $itemid]);
2432 throw new InternalServerErrorException("DB error");
2436 $user_info = api_get_user($a);
2437 $rets = api_format_items($item, $user_info, false, $type);
2440 $data = ['status' => $ret];
2444 $data = api_rss_extra($a, $data, $user_info);
2447 return api_format_data("status", $type, $data);
2450 /// @TODO move to top of file or somewhere better
2451 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2452 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2455 * Returns the most recent favorite statuses.
2457 * @param string $type Return type (atom, rss, xml, json)
2459 * @return string|array
2461 function api_favorites($type)
2466 $user_info = api_get_user($a);
2468 if (api_user() === false || $user_info === false) {
2469 throw new ForbiddenException();
2474 // in friendica starred item are private
2475 // return favorites only for self
2476 logger('api_favorites: self:' . $user_info['self']);
2478 if ($user_info['self'] == 0) {
2484 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2485 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2486 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2487 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2492 $start = $page*$count;
2495 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2498 $r = q("SELECT `item`.* FROM `item`
2499 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2500 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2501 WHERE `item`.`uid` = %d
2502 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2503 AND `item`.`starred`
2506 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2513 $ret = api_format_items($r, $user_info, false, $type);
2516 $data = ['status' => $ret];
2520 $data = api_rss_extra($a, $data, $user_info);
2523 return api_format_data("statuses", $type, $data);
2526 /// @TODO move to top of file or somewhere better
2527 api_register_func('api/favorites', 'api_favorites', true);
2531 * @param array $item
2532 * @param array $recipient
2533 * @param array $sender
2537 function api_format_messages($item, $recipient, $sender)
2539 // standard meta information
2541 'id' => $item['id'],
2542 'sender_id' => $sender['id'] ,
2544 'recipient_id' => $recipient['id'],
2545 'created_at' => api_date($item['created']),
2546 'sender_screen_name' => $sender['screen_name'],
2547 'recipient_screen_name' => $recipient['screen_name'],
2548 'sender' => $sender,
2549 'recipient' => $recipient,
2551 'friendica_seen' => $item['seen'],
2552 'friendica_parent_uri' => $item['parent-uri'],
2555 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2556 unset($ret["sender"]["uid"]);
2557 unset($ret["sender"]["self"]);
2558 unset($ret["recipient"]["uid"]);
2559 unset($ret["recipient"]["self"]);
2561 //don't send title to regular StatusNET requests to avoid confusing these apps
2562 if (x($_GET, 'getText')) {
2563 $ret['title'] = $item['title'];
2564 if ($_GET['getText'] == 'html') {
2565 $ret['text'] = BBCode::convert($item['body'], false);
2566 } elseif ($_GET['getText'] == 'plain') {
2567 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2570 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2572 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2573 unset($ret['sender']);
2574 unset($ret['recipient']);
2582 * @param array $item
2586 function api_convert_item($item)
2588 $body = $item['body'];
2589 $attachments = api_get_attachments($body);
2591 // Workaround for ostatus messages where the title is identically to the body
2592 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2593 $statusbody = trim(HTML::toPlaintext($html, 0));
2595 // handle data: images
2596 $statusbody = api_format_items_embeded_images($item, $statusbody);
2598 $statustitle = trim($item['title']);
2600 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2601 $statustext = trim($statusbody);
2603 $statustext = trim($statustitle."\n\n".$statusbody);
2606 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2607 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2610 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2612 // Workaround for clients with limited HTML parser functionality
2613 $search = ["<br>", "<blockquote>", "</blockquote>",
2614 "<h1>", "</h1>", "<h2>", "</h2>",
2615 "<h3>", "</h3>", "<h4>", "</h4>",
2616 "<h5>", "</h5>", "<h6>", "</h6>"];
2617 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2618 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2619 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2620 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2621 $statushtml = str_replace($search, $replace, $statushtml);
2623 if ($item['title'] != "") {
2624 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2628 $oldtext = $statushtml;
2629 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2630 } while ($oldtext != $statushtml);
2632 if (substr($statushtml, 0, 4) == '<br>') {
2633 $statushtml = substr($statushtml, 4);
2636 if (substr($statushtml, 0, -4) == '<br>') {
2637 $statushtml = substr($statushtml, -4);
2640 // feeds without body should contain the link
2641 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2642 $statushtml .= BBCode::convert($item['plink']);
2645 $entities = api_get_entitities($statustext, $body);
2648 "text" => $statustext,
2649 "html" => $statushtml,
2650 "attachments" => $attachments,
2651 "entities" => $entities
2657 * @param string $body
2661 function api_get_attachments(&$body)
2664 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2666 $URLSearchString = "^\[\]";
2667 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2675 foreach ($images[1] as $image) {
2676 $imagedata = Image::getInfoFromURL($image);
2679 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2683 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2684 foreach ($images[0] as $orig) {
2685 $body = str_replace($orig, "", $body);
2689 return $attachments;
2694 * @param string $text
2695 * @param string $bbcode
2698 * @todo Links at the first character of the post
2700 function api_get_entitities(&$text, $bbcode)
2702 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2704 if ($include_entities != "true") {
2705 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2707 foreach ($images[1] as $image) {
2708 $replace = proxy_url($image);
2709 $text = str_replace($image, $replace, $text);
2714 $bbcode = BBCode::cleanPictureLinks($bbcode);
2716 // Change pure links in text to bbcode uris
2717 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2720 $entities["hashtags"] = [];
2721 $entities["symbols"] = [];
2722 $entities["urls"] = [];
2723 $entities["user_mentions"] = [];
2725 $URLSearchString = "^\[\]";
2727 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2729 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2730 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2731 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2733 $bbcode = preg_replace(
2734 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2735 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2738 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2740 $bbcode = preg_replace(
2741 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2742 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2745 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2747 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2749 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2750 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2753 foreach ($urls[1] as $id => $url) {
2754 //$start = strpos($text, $url, $offset);
2755 $start = iconv_strpos($text, $url, 0, "UTF-8");
2756 if (!($start === false)) {
2757 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2761 ksort($ordered_urls);
2764 //foreach ($urls[1] AS $id=>$url) {
2765 foreach ($ordered_urls as $url) {
2766 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2767 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2769 $display_url = $url["title"];
2771 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2772 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2774 if (strlen($display_url) > 26) {
2775 $display_url = substr($display_url, 0, 25)."…";
2779 //$start = strpos($text, $url, $offset);
2780 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2781 if (!($start === false)) {
2782 $entities["urls"][] = ["url" => $url["url"],
2783 "expanded_url" => $url["url"],
2784 "display_url" => $display_url,
2785 "indices" => [$start, $start+strlen($url["url"])]];
2786 $offset = $start + 1;
2790 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2791 $ordered_images = [];
2792 foreach ($images[1] as $image) {
2793 //$start = strpos($text, $url, $offset);
2794 $start = iconv_strpos($text, $image, 0, "UTF-8");
2795 if (!($start === false)) {
2796 $ordered_images[$start] = $image;
2799 //$entities["media"] = array();
2802 foreach ($ordered_images as $url) {
2803 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2804 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2806 if (strlen($display_url) > 26) {
2807 $display_url = substr($display_url, 0, 25)."…";
2810 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2811 if (!($start === false)) {
2812 $image = Image::getInfoFromURL($url);
2814 // If image cache is activated, then use the following sizes:
2815 // thumb (150), small (340), medium (600) and large (1024)
2816 if (!Config::get("system", "proxy_disabled")) {
2817 $media_url = proxy_url($url);
2820 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2821 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2823 if (($image[0] > 150) || ($image[1] > 150)) {
2824 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2825 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2828 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2829 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2831 if (($image[0] > 600) || ($image[1] > 600)) {
2832 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2833 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2837 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2840 $entities["media"][] = [
2842 "id_str" => (string)$start+1,
2843 "indices" => [$start, $start+strlen($url)],
2844 "media_url" => normalise_link($media_url),
2845 "media_url_https" => $media_url,
2847 "display_url" => $display_url,
2848 "expanded_url" => $url,
2852 $offset = $start + 1;
2861 * @param array $item
2862 * @param string $text
2866 function api_format_items_embeded_images($item, $text)
2868 $text = preg_replace_callback(
2869 '|data:image/([^;]+)[^=]+=*|m',
2870 function () use ($item) {
2871 return System::baseUrl() . '/display/' . $item['guid'];
2879 * @brief return <a href='url'>name</a> as array
2881 * @param string $txt text
2886 function api_contactlink_to_array($txt)
2889 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2890 if ($r && count($match)==3) {
2892 'name' => $match[2],
2906 * @brief return likes, dislikes and attend status for item
2908 * @param array $item array
2909 * @param string $type Return type (atom, rss, xml, json)
2912 * likes => int count,
2913 * dislikes => int count
2915 function api_format_items_activities(&$item, $type = "json")
2924 'attendmaybe' => [],
2928 'SELECT * FROM `item`
2929 WHERE `uid` = %d AND `thr-parent` = "%s" AND `visible` AND NOT `deleted`',
2930 intval($item['uid']),
2934 foreach ($items as $i) {
2935 // not used as result should be structured like other user data
2936 //builtin_activity_puller($i, $activities);
2938 // get user data and add it to the array of the activity
2939 $user = api_get_user($a, $i['author-id']);
2940 switch ($i['verb']) {
2942 $activities['like'][] = $user;
2944 case ACTIVITY_DISLIKE:
2945 $activities['dislike'][] = $user;
2947 case ACTIVITY_ATTEND:
2948 $activities['attendyes'][] = $user;
2950 case ACTIVITY_ATTENDNO:
2951 $activities['attendno'][] = $user;
2953 case ACTIVITY_ATTENDMAYBE:
2954 $activities['attendmaybe'][] = $user;
2961 if ($type == "xml") {
2962 $xml_activities = [];
2963 foreach ($activities as $k => $v) {
2964 // change xml element from "like" to "friendica:like"
2965 $xml_activities["friendica:".$k] = $v;
2966 // add user data into xml output
2968 foreach ($v as $user) {
2969 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2972 $activities = $xml_activities;
2980 * @brief return data from profiles
2982 * @param array $profile_row array containing data from db table 'profile'
2985 function api_format_items_profiles($profile_row)
2988 'profile_id' => $profile_row['id'],
2989 'profile_name' => $profile_row['profile-name'],
2990 'is_default' => $profile_row['is-default'] ? true : false,
2991 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2992 'profile_photo' => $profile_row['photo'],
2993 'profile_thumb' => $profile_row['thumb'],
2994 'publish' => $profile_row['publish'] ? true : false,
2995 'net_publish' => $profile_row['net-publish'] ? true : false,
2996 'description' => $profile_row['pdesc'],
2997 'date_of_birth' => $profile_row['dob'],
2998 'address' => $profile_row['address'],
2999 'city' => $profile_row['locality'],
3000 'region' => $profile_row['region'],
3001 'postal_code' => $profile_row['postal-code'],
3002 'country' => $profile_row['country-name'],
3003 'hometown' => $profile_row['hometown'],
3004 'gender' => $profile_row['gender'],
3005 'marital' => $profile_row['marital'],
3006 'marital_with' => $profile_row['with'],
3007 'marital_since' => $profile_row['howlong'],
3008 'sexual' => $profile_row['sexual'],
3009 'politic' => $profile_row['politic'],
3010 'religion' => $profile_row['religion'],
3011 'public_keywords' => $profile_row['pub_keywords'],
3012 'private_keywords' => $profile_row['prv_keywords'],
3013 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
3014 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
3015 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
3016 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
3017 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
3018 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
3019 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
3020 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
3021 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
3022 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
3023 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
3024 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
3025 'homepage' => $profile_row['homepage'],
3032 * @brief format items to be returned by api
3034 * @param array $r array of items
3035 * @param array $user_info
3036 * @param bool $filter_user filter items by $user_info
3037 * @param string $type Return type (atom, rss, xml, json)
3039 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3045 foreach ($r as $item) {
3046 localize_item($item);
3047 list($status_user, $owner_user) = api_item_get_user($a, $item);
3049 // Look if the posts are matching if they should be filtered by user id
3050 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3054 $in_reply_to = api_in_reply_to($item);
3056 $converted = api_convert_item($item);
3058 if ($type == "xml") {
3059 $geo = "georss:point";
3065 'text' => $converted["text"],
3066 'truncated' => false,
3067 'created_at'=> api_date($item['created']),
3068 'in_reply_to_status_id' => $in_reply_to['status_id'],
3069 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3070 'source' => (($item['app']) ? $item['app'] : 'web'),
3071 'id' => intval($item['id']),
3072 'id_str' => (string) intval($item['id']),
3073 'in_reply_to_user_id' => $in_reply_to['user_id'],
3074 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3075 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3077 'favorited' => $item['starred'] ? true : false,
3078 'user' => $status_user ,
3079 'friendica_owner' => $owner_user,
3080 //'entities' => NULL,
3081 'statusnet_html' => $converted["html"],
3082 'statusnet_conversation_id' => $item['parent'],
3083 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3084 'friendica_activities' => api_format_items_activities($item, $type),
3087 if (count($converted["attachments"]) > 0) {
3088 $status["attachments"] = $converted["attachments"];
3091 if (count($converted["entities"]) > 0) {
3092 $status["entities"] = $converted["entities"];
3095 if ($status["source"] == 'web') {
3096 $status["source"] = ContactSelector::networkToName($item['network'], $user_info['url']);
3097 } elseif (ContactSelector::networkToName($item['network'], $user_info['url']) != $status["source"]) {
3098 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $user_info['url']).')');
3101 if ($item["id"] == $item["parent"]) {
3102 $retweeted_item = api_share_as_retweet($item);
3103 if ($retweeted_item !== false) {
3104 $retweeted_status = $status;
3106 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3107 } catch (BadRequestException $e) {
3108 // user not found. should be found?
3109 /// @todo check if the user should be always found
3110 $retweeted_status["user"] = [];
3113 $rt_converted = api_convert_item($retweeted_item);
3115 $retweeted_status['text'] = $rt_converted["text"];
3116 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3117 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3118 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3119 $status['retweeted_status'] = $retweeted_status;
3123 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3124 unset($status["user"]["uid"]);
3125 unset($status["user"]["self"]);
3127 if ($item["coord"] != "") {
3128 $coords = explode(' ', $item["coord"]);
3129 if (count($coords) == 2) {
3130 if ($type == "json") {
3131 $status["geo"] = ['type' => 'Point',
3132 'coordinates' => [(float) $coords[0],
3133 (float) $coords[1]]];
3134 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3135 $status["georss:point"] = $item["coord"];
3145 * Returns the remaining number of API requests available to the user before the API limit is reached.
3147 * @param string $type Return type (atom, rss, xml, json)
3149 * @return array|string
3151 function api_account_rate_limit_status($type)
3153 if ($type == "xml") {
3155 'remaining-hits' => '150',
3156 '@attributes' => ["type" => "integer"],
3157 'hourly-limit' => '150',
3158 '@attributes2' => ["type" => "integer"],
3159 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3160 '@attributes3' => ["type" => "datetime"],
3161 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3162 '@attributes4' => ["type" => "integer"],
3166 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3167 'remaining_hits' => '150',
3168 'hourly_limit' => '150',
3169 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3173 return api_format_data('hash', $type, ['hash' => $hash]);
3176 /// @TODO move to top of file or somewhere better
3177 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3180 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3182 * @param string $type Return type (atom, rss, xml, json)
3184 * @return array|string
3186 function api_help_test($type)
3188 if ($type == 'xml') {
3194 return api_format_data('ok', $type, ["ok" => $ok]);
3197 /// @TODO move to top of file or somewhere better
3198 api_register_func('api/help/test', 'api_help_test', false);
3201 * Returns all lists the user subscribes to.
3203 * @param string $type Return type (atom, rss, xml, json)
3205 * @return array|string
3206 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3208 function api_lists_list($type)
3211 /// @TODO $ret is not filled here?
3212 return api_format_data('lists', $type, ["lists_list" => $ret]);
3215 /// @TODO move to top of file or somewhere better
3216 api_register_func('api/lists/list', 'api_lists_list', true);
3217 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3220 * Returns all groups the user owns.
3222 * @param string $type Return type (atom, rss, xml, json)
3224 * @return array|string
3225 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3227 function api_lists_ownerships($type)
3231 if (api_user() === false) {
3232 throw new ForbiddenException();
3236 $user_info = api_get_user($a);
3237 $uid = $user_info['uid'];
3239 $groups = dba::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3241 // loop through all groups
3243 foreach ($groups as $group) {
3244 if ($group['visible']) {
3250 'name' => $group['name'],
3251 'id' => intval($group['id']),
3252 'id_str' => (string) $group['id'],
3253 'user' => $user_info,
3257 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3260 /// @TODO move to top of file or somewhere better
3261 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3264 * Returns recent statuses from users in the specified group.
3266 * @param string $type Return type (atom, rss, xml, json)
3268 * @return array|string
3269 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3271 function api_lists_statuses($type)
3275 $user_info = api_get_user($a);
3276 if (api_user() === false || $user_info === false) {
3277 throw new ForbiddenException();
3280 unset($_REQUEST["user_id"]);
3281 unset($_GET["user_id"]);
3283 unset($_REQUEST["screen_name"]);
3284 unset($_GET["screen_name"]);
3286 if (empty($_REQUEST['list_id'])) {
3287 throw new BadRequestException('list_id not specified');
3291 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
3292 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
3296 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3297 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3298 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
3299 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
3301 $start = $page * $count;
3305 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
3307 if ($exclude_replies > 0) {
3308 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
3310 if ($conversation_id > 0) {
3311 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
3314 $statuses = dba::p("SELECT `item`.* FROM `item`
3315 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
3316 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
3317 STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = `item`.`contact-id`
3318 WHERE `item`.`uid` = ? AND `verb` = ?
3319 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
3322 AND `group_member`.`gid` = ?
3323 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count),
3327 $_REQUEST['list_id']
3330 $items = api_format_items(dba::inArray($statuses), $user_info, false, $type);
3332 $data = ['status' => $items];
3336 $data = api_rss_extra($a, $data, $user_info);
3340 return api_format_data("statuses", $type, $data);
3343 /// @TODO move to top of file or somewhere better
3344 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3347 * Considers friends and followers lists to be private and won't return
3348 * anything if any user_id parameter is passed.
3350 * @brief Returns either the friends of the follower list
3352 * @param string $qtype Either "friends" or "followers"
3353 * @return boolean|array
3354 * @throws ForbiddenException
3356 function api_statuses_f($qtype)
3360 if (api_user() === false) {
3361 throw new ForbiddenException();
3365 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3366 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3370 $start = ($page - 1) * $count;
3372 $user_info = api_get_user($a);
3374 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3375 /* this is to stop Hotot to load friends multiple times
3376 * I'm not sure if I'm missing return something or
3377 * is a bug in hotot. Workaround, meantime
3381 return array('$users' => $ret);*/
3386 if ($qtype == 'friends') {
3387 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3388 } elseif ($qtype == 'followers') {
3389 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3392 // friends and followers only for self
3393 if ($user_info['self'] == 0) {
3394 $sql_extra = " AND false ";
3397 if ($qtype == 'blocks') {
3398 $sql_filter = 'AND `blocked` AND NOT `pending`';
3399 } elseif ($qtype == 'incoming') {
3400 $sql_filter = 'AND `pending`';
3402 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3420 foreach ($r as $cid) {
3421 $user = api_get_user($a, $cid['nurl']);
3422 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3423 unset($user["uid"]);
3424 unset($user["self"]);
3431 return ['user' => $ret];
3436 * Returns the user's friends.
3438 * @brief Returns the list of friends of the provided user
3440 * @deprecated By Twitter API in favor of friends/list
3442 * @param string $type Either "json" or "xml"
3443 * @return boolean|string|array
3445 function api_statuses_friends($type)
3447 $data = api_statuses_f("friends");
3448 if ($data === false) {
3451 return api_format_data("users", $type, $data);
3455 * Returns the user's followers.
3457 * @brief Returns the list of followers of the provided user
3459 * @deprecated By Twitter API in favor of friends/list
3461 * @param string $type Either "json" or "xml"
3462 * @return boolean|string|array
3464 function api_statuses_followers($type)
3466 $data = api_statuses_f("followers");
3467 if ($data === false) {
3470 return api_format_data("users", $type, $data);
3473 /// @TODO move to top of file or somewhere better
3474 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3475 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3478 * Returns the list of blocked users
3480 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3482 * @param string $type Either "json" or "xml"
3484 * @return boolean|string|array
3486 function api_blocks_list($type)
3488 $data = api_statuses_f('blocks');
3489 if ($data === false) {
3492 return api_format_data("users", $type, $data);
3495 /// @TODO move to top of file or somewhere better
3496 api_register_func('api/blocks/list', 'api_blocks_list', true);
3499 * Returns the list of pending users IDs
3501 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3503 * @param string $type Either "json" or "xml"
3505 * @return boolean|string|array
3507 function api_friendships_incoming($type)
3509 $data = api_statuses_f('incoming');
3510 if ($data === false) {
3515 foreach ($data['user'] as $user) {
3516 $ids[] = $user['id'];
3519 return api_format_data("ids", $type, ['id' => $ids]);
3522 /// @TODO move to top of file or somewhere better
3523 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3526 * Returns the instance's configuration information.
3528 * @param string $type Return type (atom, rss, xml, json)
3530 * @return array|string
3532 function api_statusnet_config($type)
3536 $name = $a->config['sitename'];
3537 $server = $a->get_hostname();
3538 $logo = System::baseUrl() . '/images/friendica-64.png';
3539 $email = $a->config['admin_email'];
3540 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3541 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3542 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3543 if ($a->config['api_import_size']) {
3544 $textlimit = (string) $a->config['api_import_size'];
3546 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3547 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3550 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3551 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3552 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3553 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3554 'shorturllength' => '30',
3556 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3557 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3558 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3559 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3564 return api_format_data('config', $type, ['config' => $config]);
3567 /// @TODO move to top of file or somewhere better
3568 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3569 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3573 * @param string $type Return type (atom, rss, xml, json)
3575 * @return array|string
3577 function api_statusnet_version($type)
3580 $fake_statusnet_version = "0.9.7";
3582 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3585 /// @TODO move to top of file or somewhere better
3586 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3587 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3591 * @param string $type Return type (atom, rss, xml, json)
3593 * @todo use api_format_data() to return data
3595 function api_ff_ids($type)
3598 throw new ForbiddenException();
3605 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3608 "SELECT `pcontact`.`id` FROM `contact`
3609 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3610 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3613 if (!DBM::is_result($r)) {
3618 foreach ($r as $rr) {
3619 if ($stringify_ids) {
3622 $ids[] = intval($rr['id']);
3626 return api_format_data("ids", $type, ['id' => $ids]);
3630 * Returns the ID of every user the user is following.
3632 * @param string $type Return type (atom, rss, xml, json)
3634 * @return array|string
3635 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3637 function api_friends_ids($type)
3639 return api_ff_ids($type);
3643 * Returns the ID of every user following the user.
3645 * @param string $type Return type (atom, rss, xml, json)
3647 * @return array|string
3648 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3650 function api_followers_ids($type)
3652 return api_ff_ids($type);
3655 /// @TODO move to top of file or somewhere better
3656 api_register_func('api/friends/ids', 'api_friends_ids', true);
3657 api_register_func('api/followers/ids', 'api_followers_ids', true);
3660 * Sends a new direct message.
3662 * @param string $type Return type (atom, rss, xml, json)
3664 * @return array|string
3665 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3667 function api_direct_messages_new($type)
3672 if (api_user() === false) {
3673 throw new ForbiddenException();
3676 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3680 $sender = api_get_user($a);
3682 if ($_POST['screen_name']) {
3684 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3686 dbesc($_POST['screen_name'])
3689 // Selecting the id by priority, friendica first
3690 api_best_nickname($r);
3692 $recipient = api_get_user($a, $r[0]['nurl']);
3694 $recipient = api_get_user($a, $_POST['user_id']);
3699 if (x($_REQUEST, 'replyto')) {
3701 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3703 intval($_REQUEST['replyto'])
3705 $replyto = $r[0]['parent-uri'];
3706 $sub = $r[0]['title'];
3708 if (x($_REQUEST, 'title')) {
3709 $sub = $_REQUEST['title'];
3711 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3715 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3718 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3719 $ret = api_format_messages($r[0], $recipient, $sender);
3721 $ret = ["error"=>$id];
3724 $data = ['direct_message'=>$ret];
3729 $data = api_rss_extra($a, $data, $sender);
3732 return api_format_data("direct-messages", $type, $data);
3735 /// @TODO move to top of file or somewhere better
3736 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3739 * Destroys a direct message.
3741 * @brief delete a direct_message from mail table through api
3743 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3744 * @return string|array
3745 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3747 function api_direct_messages_destroy($type)
3751 if (api_user() === false) {
3752 throw new ForbiddenException();
3756 $user_info = api_get_user($a);
3758 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3760 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3761 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3762 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3764 $uid = $user_info['uid'];
3765 // error if no id or parenturi specified (for clients posting parent-uri as well)
3766 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3767 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3768 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3771 // BadRequestException if no id specified (for clients using Twitter API)
3773 throw new BadRequestException('Message id not specified');
3776 // add parent-uri to sql command if specified by calling app
3777 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3779 // get data of the specified message id
3781 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3786 // error message if specified id is not in database
3787 if (!DBM::is_result($r)) {
3788 if ($verbose == "true") {
3789 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3790 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3792 /// @todo BadRequestException ok for Twitter API clients?
3793 throw new BadRequestException('message id not in database');
3798 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3803 if ($verbose == "true") {
3806 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3807 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3809 $answer = ['result' => 'error', 'message' => 'unknown error'];
3810 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3813 /// @todo return JSON data like Twitter API not yet implemented
3816 /// @TODO move to top of file or somewhere better
3817 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3821 * @param string $type Return type (atom, rss, xml, json)
3822 * @param string $box
3823 * @param string $verbose
3825 * @return array|string
3827 function api_direct_messages_box($type, $box, $verbose)
3830 $user_info = api_get_user($a);
3832 if (api_user() === false || $user_info === false) {
3833 throw new ForbiddenException();
3837 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3838 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3843 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3844 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3846 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3847 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3850 unset($_REQUEST["user_id"]);
3851 unset($_GET["user_id"]);
3853 unset($_REQUEST["screen_name"]);
3854 unset($_GET["screen_name"]);
3856 $profile_url = $user_info["url"];
3859 $start = $page * $count;
3864 if ($box=="sentbox") {
3865 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3866 } elseif ($box == "conversation") {
3867 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3868 } elseif ($box == "all") {
3869 $sql_extra = "true";
3870 } elseif ($box == "inbox") {
3871 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3875 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3878 if ($user_id != "") {
3879 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3880 } elseif ($screen_name !="") {
3881 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3885 "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",
3891 if ($verbose == "true" && !DBM::is_result($r)) {
3892 $answer = ['result' => 'error', 'message' => 'no mails available'];
3893 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3897 foreach ($r as $item) {
3898 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3899 $recipient = $user_info;
3900 $sender = api_get_user($a, normalise_link($item['contact-url']));
3901 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3902 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3903 $sender = $user_info;
3906 if (isset($recipient) && isset($sender)) {
3907 $ret[] = api_format_messages($item, $recipient, $sender);
3912 $data = ['direct_message' => $ret];
3916 $data = api_rss_extra($a, $data, $user_info);
3919 return api_format_data("direct-messages", $type, $data);
3923 * Returns the most recent direct messages sent by the user.
3925 * @param string $type Return type (atom, rss, xml, json)
3927 * @return array|string
3928 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3930 function api_direct_messages_sentbox($type)
3932 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3933 return api_direct_messages_box($type, "sentbox", $verbose);
3937 * Returns the most recent direct messages sent to the user.
3939 * @param string $type Return type (atom, rss, xml, json)
3941 * @return array|string
3942 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3944 function api_direct_messages_inbox($type)
3946 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3947 return api_direct_messages_box($type, "inbox", $verbose);
3952 * @param string $type Return type (atom, rss, xml, json)
3954 * @return array|string
3956 function api_direct_messages_all($type)
3958 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3959 return api_direct_messages_box($type, "all", $verbose);
3964 * @param string $type Return type (atom, rss, xml, json)
3966 * @return array|string
3968 function api_direct_messages_conversation($type)
3970 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3971 return api_direct_messages_box($type, "conversation", $verbose);
3974 /// @TODO move to top of file or somewhere better
3975 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3976 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3977 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3978 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3981 * Returns an OAuth Request Token.
3983 * @see https://oauth.net/core/1.0/#auth_step1
3985 function api_oauth_request_token()
3987 $oauth1 = new FKOAuth1();
3989 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3990 } catch (Exception $e) {
3991 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3999 * Returns an OAuth Access Token.
4001 * @return array|string
4002 * @see https://oauth.net/core/1.0/#auth_step3
4004 function api_oauth_access_token()
4006 $oauth1 = new FKOAuth1();
4008 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4009 } catch (Exception $e) {
4010 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4017 /// @TODO move to top of file or somewhere better
4018 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4019 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4023 * @brief delete a complete photoalbum with all containing photos from database through api
4025 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4026 * @return string|array
4028 function api_fr_photoalbum_delete($type)
4030 if (api_user() === false) {
4031 throw new ForbiddenException();
4034 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4036 // we do not allow calls without album string
4038 throw new BadRequestException("no albumname specified");
4040 // check if album is existing
4042 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4046 if (!DBM::is_result($r)) {
4047 throw new BadRequestException("album not available");
4050 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4051 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4052 foreach ($r as $rr) {
4054 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4055 intval(local_user()),
4056 dbesc($rr['resource-id'])
4059 if (!DBM::is_result($photo_item)) {
4060 throw new InternalServerErrorException("problem with deleting items occured");
4062 Item::deleteForUser(['id' => $photo_item[0]['id']], api_user());
4065 // now let's delete all photos from the album
4066 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
4068 // return success of deletion or error message
4070 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4071 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4073 throw new InternalServerErrorException("unknown error - deleting from database failed");
4078 * @brief update the name of the album for all photos of an album
4080 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4081 * @return string|array
4083 function api_fr_photoalbum_update($type)
4085 if (api_user() === false) {
4086 throw new ForbiddenException();
4089 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4090 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4092 // we do not allow calls without album string
4094 throw new BadRequestException("no albumname specified");
4096 if ($album_new == "") {
4097 throw new BadRequestException("no new albumname specified");
4099 // check if album is existing
4100 if (!dba::exists('photo', ['uid' => api_user(), 'album' => $album])) {
4101 throw new BadRequestException("album not available");
4103 // now let's update all photos to the albumname
4104 $result = dba::update('photo', ['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4106 // return success of updating or error message
4108 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4109 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4111 throw new InternalServerErrorException("unknown error - updating in database failed");
4117 * @brief list all photos of the authenticated user
4119 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4120 * @return string|array
4122 function api_fr_photos_list($type)
4124 if (api_user() === false) {
4125 throw new ForbiddenException();
4128 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4129 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4130 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4131 intval(local_user())
4134 'image/jpeg' => 'jpg',
4135 'image/png' => 'png',
4136 'image/gif' => 'gif'
4138 $data = ['photo'=>[]];
4139 if (DBM::is_result($r)) {
4140 foreach ($r as $rr) {
4142 $photo['id'] = $rr['resource-id'];
4143 $photo['album'] = $rr['album'];
4144 $photo['filename'] = $rr['filename'];
4145 $photo['type'] = $rr['type'];
4146 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4147 $photo['created'] = $rr['created'];
4148 $photo['edited'] = $rr['edited'];
4149 $photo['desc'] = $rr['desc'];
4151 if ($type == "xml") {
4152 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4154 $photo['thumb'] = $thumb;
4155 $data['photo'][] = $photo;
4159 return api_format_data("photos", $type, $data);
4163 * @brief upload a new photo or change an existing photo
4165 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4166 * @return string|array
4168 function api_fr_photo_create_update($type)
4170 if (api_user() === false) {
4171 throw new ForbiddenException();
4174 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4175 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4176 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4177 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4178 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4179 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4180 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4181 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4182 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4184 // do several checks on input parameters
4185 // we do not allow calls without album string
4186 if ($album == null) {
4187 throw new BadRequestException("no albumname specified");
4189 // if photo_id == null --> we are uploading a new photo
4190 if ($photo_id == null) {
4193 // error if no media posted in create-mode
4194 if (!x($_FILES, 'media')) {
4196 throw new BadRequestException("no media data submitted");
4199 // album_new will be ignored in create-mode
4204 // check if photo is existing in database
4206 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4211 if (!DBM::is_result($r)) {
4212 throw new BadRequestException("photo not available");
4216 // checks on acl strings provided by clients
4217 $acl_input_error = false;
4218 $acl_input_error |= check_acl_input($allow_cid);
4219 $acl_input_error |= check_acl_input($deny_cid);
4220 $acl_input_error |= check_acl_input($allow_gid);
4221 $acl_input_error |= check_acl_input($deny_gid);
4222 if ($acl_input_error) {
4223 throw new BadRequestException("acl data invalid");
4225 // now let's upload the new media in create-mode
4226 if ($mode == "create") {
4227 $media = $_FILES['media'];
4228 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4230 // return success of updating or error message
4231 if (!is_null($data)) {
4232 return api_format_data("photo_create", $type, $data);
4234 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4238 // now let's do the changes in update-mode
4239 if ($mode == "update") {
4242 if (!is_null($desc)) {
4243 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4246 if (!is_null($album_new)) {
4247 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4250 if (!is_null($allow_cid)) {
4251 $allow_cid = trim($allow_cid);
4252 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4255 if (!is_null($deny_cid)) {
4256 $deny_cid = trim($deny_cid);
4257 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4260 if (!is_null($allow_gid)) {
4261 $allow_gid = trim($allow_gid);
4262 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4265 if (!is_null($deny_gid)) {
4266 $deny_gid = trim($deny_gid);
4267 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4271 if ($sql_extra != "") {
4272 $nothingtodo = false;
4274 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4276 DateTimeFormat::utcNow(), // update edited timestamp
4282 $nothingtodo = true;
4285 if (x($_FILES, 'media')) {
4286 $nothingtodo = false;
4287 $media = $_FILES['media'];
4288 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4289 if (!is_null($data)) {
4290 return api_format_data("photo_update", $type, $data);
4294 // return success of updating or error message
4296 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4297 return api_format_data("photo_update", $type, ['$result' => $answer]);
4300 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4301 return api_format_data("photo_update", $type, ['$result' => $answer]);
4303 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4306 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4310 * @brief delete a single photo from the database through api
4312 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4313 * @return string|array
4315 function api_fr_photo_delete($type)
4317 if (api_user() === false) {
4318 throw new ForbiddenException();
4321 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4323 // do several checks on input parameters
4324 // we do not allow calls without photo id
4325 if ($photo_id == null) {
4326 throw new BadRequestException("no photo_id specified");
4328 // check if photo is existing in database
4330 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4334 if (!DBM::is_result($r)) {
4335 throw new BadRequestException("photo not available");
4337 // now we can perform on the deletion of the photo
4338 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4340 // return success of deletion or error message
4342 // retrieve the id of the parent element (the photo element)
4344 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4345 intval(local_user()),
4349 if (!DBM::is_result($photo_item)) {
4350 throw new InternalServerErrorException("problem with deleting items occured");
4352 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4353 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4354 Item::deleteForUser(['id' => $photo_item[0]['id']], api_user());
4356 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4357 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4359 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4365 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4367 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4368 * @return string|array
4370 function api_fr_photo_detail($type)
4372 if (api_user() === false) {
4373 throw new ForbiddenException();
4375 if (!x($_REQUEST, 'photo_id')) {
4376 throw new BadRequestException("No photo id.");
4379 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4380 $photo_id = $_REQUEST['photo_id'];
4382 // prepare json/xml output with data from database for the requested photo
4383 $data = prepare_photo_data($type, $scale, $photo_id);
4385 return api_format_data("photo_detail", $type, $data);
4390 * Updates the user’s profile image.
4392 * @brief updates the profile image for the user (either a specified profile or the default profile)
4394 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4396 * @return string|array
4397 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4399 function api_account_update_profile_image($type)
4401 if (api_user() === false) {
4402 throw new ForbiddenException();
4405 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4407 // error if image data is missing
4408 if (!x($_FILES, 'image')) {
4409 throw new BadRequestException("no media data submitted");
4412 // check if specified profile id is valid
4413 if ($profile_id != 0) {
4414 $profile = dba::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4415 // error message if specified profile id is not in database
4416 if (!DBM::is_result($profile)) {
4417 throw new BadRequestException("profile_id not available");
4419 $is_default_profile = $profile['is-default'];
4421 $is_default_profile = 1;
4424 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4426 if (x($_FILES, 'image')) {
4427 $media = $_FILES['image'];
4428 } elseif (x($_FILES, 'media')) {
4429 $media = $_FILES['media'];
4431 // save new profile image
4432 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4435 if (is_array($media['type'])) {
4436 $filetype = $media['type'][0];
4438 $filetype = $media['type'];
4440 if ($filetype == "image/jpeg") {
4442 } elseif ($filetype == "image/png") {
4445 throw new InternalServerErrorException('Unsupported filetype');
4448 // change specified profile or all profiles to the new resource-id
4449 if ($is_default_profile) {
4450 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4451 dba::update('photo', ['profile' => false], $condition);
4453 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4454 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4455 dba::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4458 Contact::updateSelfFromUserID(api_user(), true);
4460 // Update global directory in background
4461 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4462 if ($url && strlen(Config::get('system', 'directory'))) {
4463 Worker::add(PRIORITY_LOW, "Directory", $url);
4466 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4468 // output for client
4470 return api_account_verify_credentials($type);
4472 // SaveMediaToDatabase failed for some reason
4473 throw new InternalServerErrorException("image upload failed");
4477 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4478 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4479 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4480 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4481 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4482 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4483 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4484 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4485 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4488 * Update user profile
4490 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4492 * @return array|string
4494 function api_account_update_profile($type)
4496 $local_user = api_user();
4497 $api_user = api_get_user(get_app());
4499 if (!empty($_POST['name'])) {
4500 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4501 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4502 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4503 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4506 if (isset($_POST['description'])) {
4507 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4508 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4509 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4512 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4513 // Update global directory in background
4514 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4515 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4518 return api_account_verify_credentials($type);
4521 /// @TODO move to top of file or somewhere better
4522 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4526 * @param string $acl_string
4528 function check_acl_input($acl_string)
4530 if ($acl_string == null || $acl_string == " ") {
4533 $contact_not_found = false;
4535 // split <x><y><z> into array of cid's
4536 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4538 // check for each cid if it is available on server
4539 $cid_array = $array[0];
4540 foreach ($cid_array as $cid) {
4541 $cid = str_replace("<", "", $cid);
4542 $cid = str_replace(">", "", $cid);
4544 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4548 $contact_not_found |= !DBM::is_result($contact);
4550 return $contact_not_found;
4555 * @param string $mediatype
4556 * @param array $media
4557 * @param string $type
4558 * @param string $album
4559 * @param string $allow_cid
4560 * @param string $deny_cid
4561 * @param string $allow_gid
4562 * @param string $deny_gid
4563 * @param string $desc
4564 * @param integer $profile
4565 * @param boolean $visibility
4566 * @param string $photo_id
4568 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)
4576 if (is_array($media)) {
4577 if (is_array($media['tmp_name'])) {
4578 $src = $media['tmp_name'][0];
4580 $src = $media['tmp_name'];
4582 if (is_array($media['name'])) {
4583 $filename = basename($media['name'][0]);
4585 $filename = basename($media['name']);
4587 if (is_array($media['size'])) {
4588 $filesize = intval($media['size'][0]);
4590 $filesize = intval($media['size']);
4592 if (is_array($media['type'])) {
4593 $filetype = $media['type'][0];
4595 $filetype = $media['type'];
4599 if ($filetype == "") {
4600 $filetype=Image::guessType($filename);
4602 $imagedata = getimagesize($src);
4604 $filetype = $imagedata['mime'];
4607 "File upload src: " . $src . " - filename: " . $filename .
4608 " - size: " . $filesize . " - type: " . $filetype,
4612 // check if there was a php upload error
4613 if ($filesize == 0 && $media['error'] == 1) {
4614 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4616 // check against max upload size within Friendica instance
4617 $maximagesize = Config::get('system', 'maximagesize');
4618 if ($maximagesize && ($filesize > $maximagesize)) {
4619 $formattedBytes = formatBytes($maximagesize);
4620 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4623 // create Photo instance with the data of the image
4624 $imagedata = @file_get_contents($src);
4625 $Image = new Image($imagedata, $filetype);
4626 if (! $Image->isValid()) {
4627 throw new InternalServerErrorException("unable to process image data");
4630 // check orientation of image
4631 $Image->orient($src);
4634 // check max length of images on server
4635 $max_length = Config::get('system', 'max_image_length');
4636 if (! $max_length) {
4637 $max_length = MAX_IMAGE_LENGTH;
4639 if ($max_length > 0) {
4640 $Image->scaleDown($max_length);
4641 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4643 $width = $Image->getWidth();
4644 $height = $Image->getHeight();
4646 // create a new resource-id if not already provided
4647 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4649 if ($mediatype == "photo") {
4650 // upload normal image (scales 0, 1, 2)
4651 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4653 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4655 logger("photo upload: image upload with scale 0 (original size) failed");
4657 if ($width > 640 || $height > 640) {
4658 $Image->scaleDown(640);
4659 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4661 logger("photo upload: image upload with scale 1 (640x640) failed");
4665 if ($width > 320 || $height > 320) {
4666 $Image->scaleDown(320);
4667 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4669 logger("photo upload: image upload with scale 2 (320x320) failed");
4672 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4673 } elseif ($mediatype == "profileimage") {
4674 // upload profile image (scales 4, 5, 6)
4675 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4677 if ($width > 175 || $height > 175) {
4678 $Image->scaleDown(175);
4679 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4681 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4685 if ($width > 80 || $height > 80) {
4686 $Image->scaleDown(80);
4687 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4689 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4693 if ($width > 48 || $height > 48) {
4694 $Image->scaleDown(48);
4695 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4697 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4700 $Image->__destruct();
4701 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4704 if (isset($r) && $r) {
4705 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4706 if ($photo_id == null && $mediatype == "photo") {
4707 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4709 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4710 return prepare_photo_data($type, false, $hash);
4712 throw new InternalServerErrorException("image upload failed");
4718 * @param string $hash
4719 * @param string $allow_cid
4720 * @param string $deny_cid
4721 * @param string $allow_gid
4722 * @param string $deny_gid
4723 * @param string $filetype
4724 * @param boolean $visibility
4726 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4728 // get data about the api authenticated user
4729 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4730 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4733 $arr['guid'] = get_guid(32);
4734 $arr['uid'] = intval(api_user());
4736 $arr['parent-uri'] = $uri;
4737 $arr['type'] = 'photo';
4739 $arr['resource-id'] = $hash;
4740 $arr['contact-id'] = $owner_record[0]['id'];
4741 $arr['owner-name'] = $owner_record[0]['name'];
4742 $arr['owner-link'] = $owner_record[0]['url'];
4743 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4744 $arr['author-name'] = $owner_record[0]['name'];
4745 $arr['author-link'] = $owner_record[0]['url'];
4746 $arr['author-avatar'] = $owner_record[0]['thumb'];
4748 $arr['allow_cid'] = $allow_cid;
4749 $arr['allow_gid'] = $allow_gid;
4750 $arr['deny_cid'] = $deny_cid;
4751 $arr['deny_gid'] = $deny_gid;
4752 $arr['visible'] = $visibility;
4756 'image/jpeg' => 'jpg',
4757 'image/png' => 'png',
4758 'image/gif' => 'gif'
4761 // adds link to the thumbnail scale photo
4762 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4763 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4766 // do the magic for storing the item in the database and trigger the federation to other contacts
4772 * @param string $type
4774 * @param string $photo_id
4778 function prepare_photo_data($type, $scale, $photo_id)
4781 $user_info = api_get_user($a);
4783 if ($user_info === false) {
4784 throw new ForbiddenException();
4787 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4788 $data_sql = ($scale === false ? "" : "data, ");
4790 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4791 // clients needs to convert this in their way for further processing
4793 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4794 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4795 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4796 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4798 intval(local_user()),
4804 'image/jpeg' => 'jpg',
4805 'image/png' => 'png',
4806 'image/gif' => 'gif'
4809 // prepare output data for photo
4810 if (DBM::is_result($r)) {
4811 $data = ['photo' => $r[0]];
4812 $data['photo']['id'] = $data['photo']['resource-id'];
4813 if ($scale !== false) {
4814 $data['photo']['data'] = base64_encode($data['photo']['data']);
4816 unset($data['photo']['datasize']); //needed only with scale param
4818 if ($type == "xml") {
4819 $data['photo']['links'] = [];
4820 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4821 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4823 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4826 $data['photo']['link'] = [];
4827 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4829 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4830 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4834 unset($data['photo']['resource-id']);
4835 unset($data['photo']['minscale']);
4836 unset($data['photo']['maxscale']);
4838 throw new NotFoundException();
4841 // retrieve item element for getting activities (like, dislike etc.) related to photo
4843 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4844 intval(local_user()),
4847 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4849 // retrieve comments on photo
4850 $r = q("SELECT `item`.* FROM `item`
4851 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
4852 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4853 WHERE `item`.`parent` = %d AND `item`.`visible`
4854 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4855 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4856 intval($item[0]['parent']),
4858 dbesc(ACTIVITY_POST)
4861 // prepare output of comments
4862 $commentData = api_format_items($r, $user_info, false, $type);
4864 if ($type == "xml") {
4866 foreach ($commentData as $comment) {
4867 $comments[$k++ . ":comment"] = $comment;
4870 foreach ($commentData as $comment) {
4871 $comments[] = $comment;
4874 $data['photo']['friendica_comments'] = $comments;
4876 // include info if rights on photo and rights on item are mismatching
4877 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4878 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4879 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4880 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4881 $data['photo']['rights_mismatch'] = $rights_mismatch;
4888 * Similar as /mod/redir.php
4889 * redirect to 'url' after dfrn auth
4891 * Why this when there is mod/redir.php already?
4892 * This use api_user() and api_login()
4895 * c_url: url of remote contact to auth to
4896 * url: string, url to redirect after auth
4898 function api_friendica_remoteauth()
4900 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4901 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4903 if ($url === '' || $c_url === '') {
4904 throw new BadRequestException("Wrong parameters.");
4907 $c_url = normalise_link($c_url);
4911 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4913 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4914 throw new BadRequestException("Unknown contact");
4917 $cid = $contact['id'];
4919 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4921 if ($contact['duplex'] && $contact['issued-id']) {
4922 $orig_id = $contact['issued-id'];
4923 $dfrn_id = '1:' . $orig_id;
4925 if ($contact['duplex'] && $contact['dfrn-id']) {
4926 $orig_id = $contact['dfrn-id'];
4927 $dfrn_id = '0:' . $orig_id;
4930 $sec = random_string();
4932 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4933 'sec' => $sec, 'expire' => time() + 45];
4934 dba::insert('profile_check', $fields);
4936 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4937 $dest = ($url ? '&destination_url=' . $url : '');
4939 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4940 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4941 . '&type=profile&sec=' . $sec . $dest
4944 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4947 * @brief Return the item shared, if the item contains only the [share] tag
4949 * @param array $item Sharer item
4950 * @return array|false Shared item or false if not a reshare
4952 function api_share_as_retweet(&$item)
4954 $body = trim($item["body"]);
4956 if (Diaspora::isReshare($body, false)===false) {
4960 /// @TODO "$1" should maybe mean '$1' ?
4961 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4963 * Skip if there is no shared message in there
4964 * we already checked this in diaspora::isReshare()
4965 * but better one more than one less...
4967 if ($body == $attributes) {
4972 // build the fake reshared item
4973 $reshared_item = $item;
4976 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4977 if ($matches[1] != "") {
4978 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4981 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4982 if ($matches[1] != "") {
4983 $author = $matches[1];
4987 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4988 if ($matches[1] != "") {
4989 $profile = $matches[1];
4992 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4993 if ($matches[1] != "") {
4994 $profile = $matches[1];
4998 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4999 if ($matches[1] != "") {
5000 $avatar = $matches[1];
5003 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5004 if ($matches[1] != "") {
5005 $avatar = $matches[1];
5009 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5010 if ($matches[1] != "") {
5011 $link = $matches[1];
5014 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5015 if ($matches[1] != "") {
5016 $link = $matches[1];
5020 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5021 if ($matches[1] != "") {
5022 $posted = $matches[1];
5025 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5026 if ($matches[1] != "") {
5027 $posted = $matches[1];
5030 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5032 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5036 $reshared_item["body"] = $shared_body;
5037 $reshared_item["author-name"] = $author;
5038 $reshared_item["author-link"] = $profile;
5039 $reshared_item["author-avatar"] = $avatar;
5040 $reshared_item["plink"] = $link;
5041 $reshared_item["created"] = $posted;
5042 $reshared_item["edited"] = $posted;
5044 return $reshared_item;
5049 * @param string $profile
5051 * @return string|false
5052 * @todo remove trailing junk from profile url
5053 * @todo pump.io check has to check the website
5055 function api_get_nick($profile)
5060 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5061 dbesc(normalise_link($profile))
5064 if (DBM::is_result($r)) {
5065 $nick = $r[0]["nick"];
5070 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5071 dbesc(normalise_link($profile))
5074 if (DBM::is_result($r)) {
5075 $nick = $r[0]["nick"];
5080 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5081 if ($friendica != $profile) {
5087 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5088 if ($diaspora != $profile) {
5094 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5095 if ($twitter != $profile) {
5102 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5103 if ($StatusnetHost != $profile) {
5104 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5105 if ($StatusnetUser != $profile) {
5106 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5107 $user = json_decode($UserData);
5109 $nick = $user->screen_name;
5115 // To-Do: look at the page if its really a pumpio site
5116 //if (!$nick == "") {
5117 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5118 // if ($pumpio != $profile)
5120 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5133 * @param array $item
5137 function api_in_reply_to($item)
5141 $in_reply_to['status_id'] = null;
5142 $in_reply_to['user_id'] = null;
5143 $in_reply_to['status_id_str'] = null;
5144 $in_reply_to['user_id_str'] = null;
5145 $in_reply_to['screen_name'] = null;
5147 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5149 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5150 intval($item['uid']),
5151 dbesc($item['thr-parent'])
5154 if (DBM::is_result($r)) {
5155 $in_reply_to['status_id'] = intval($r[0]['id']);
5157 $in_reply_to['status_id'] = intval($item['parent']);
5160 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5163 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM `item`
5164 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5165 WHERE `item`.`id` = %d LIMIT 1",
5166 intval($in_reply_to['status_id'])
5169 if (DBM::is_result($r)) {
5170 if ($r[0]['nick'] == "") {
5171 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5174 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5175 $in_reply_to['user_id'] = intval($r[0]['id']);
5176 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5179 // There seems to be situation, where both fields are identical:
5180 // https://github.com/friendica/friendica/issues/1010
5181 // This is a bugfix for that.
5182 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5183 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5184 $in_reply_to['status_id'] = null;
5185 $in_reply_to['user_id'] = null;
5186 $in_reply_to['status_id_str'] = null;
5187 $in_reply_to['user_id_str'] = null;
5188 $in_reply_to['screen_name'] = null;
5192 return $in_reply_to;
5197 * @param string $text
5201 function api_clean_plain_items($text)
5203 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5205 $text = BBCode::cleanPictureLinks($text);
5206 $URLSearchString = "^\[\]";
5208 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5210 if ($include_entities == "true") {
5211 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5214 // Simplify "attachment" element
5215 $text = api_clean_attachments($text);
5221 * @brief Removes most sharing information for API text export
5223 * @param string $body The original body
5225 * @return string Cleaned body
5227 function api_clean_attachments($body)
5229 $data = BBCode::getAttachmentData($body);
5236 if (isset($data["text"])) {
5237 $body = $data["text"];
5239 if (($body == "") && isset($data["title"])) {
5240 $body = $data["title"];
5242 if (isset($data["url"])) {
5243 $body .= "\n".$data["url"];
5245 $body .= $data["after"];
5252 * @param array $contacts
5256 function api_best_nickname(&$contacts)
5260 if (count($contacts) == 0) {
5264 foreach ($contacts as $contact) {
5265 if ($contact["network"] == "") {
5266 $contact["network"] = "dfrn";
5267 $best_contact = [$contact];
5271 if (sizeof($best_contact) == 0) {
5272 foreach ($contacts as $contact) {
5273 if ($contact["network"] == "dfrn") {
5274 $best_contact = [$contact];
5279 if (sizeof($best_contact) == 0) {
5280 foreach ($contacts as $contact) {
5281 if ($contact["network"] == "dspr") {
5282 $best_contact = [$contact];
5287 if (sizeof($best_contact) == 0) {
5288 foreach ($contacts as $contact) {
5289 if ($contact["network"] == "stat") {
5290 $best_contact = [$contact];
5295 if (sizeof($best_contact) == 0) {
5296 foreach ($contacts as $contact) {
5297 if ($contact["network"] == "pump") {
5298 $best_contact = [$contact];
5303 if (sizeof($best_contact) == 0) {
5304 foreach ($contacts as $contact) {
5305 if ($contact["network"] == "twit") {
5306 $best_contact = [$contact];
5311 if (sizeof($best_contact) == 1) {
5312 $contacts = $best_contact;
5314 $contacts = [$contacts[0]];
5319 * Return all or a specified group of the user with the containing contacts.
5321 * @param string $type Return type (atom, rss, xml, json)
5323 * @return array|string
5325 function api_friendica_group_show($type)
5329 if (api_user() === false) {
5330 throw new ForbiddenException();
5334 $user_info = api_get_user($a);
5335 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5336 $uid = $user_info['uid'];
5338 // get data of the specified group id or all groups if not specified
5341 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5345 // error message if specified gid is not in database
5346 if (!DBM::is_result($r)) {
5347 throw new BadRequestException("gid not available");
5351 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5356 // loop through all groups and retrieve all members for adding data in the user array
5358 foreach ($r as $rr) {
5359 $members = Contact::getByGroupId($rr['id']);
5362 if ($type == "xml") {
5363 $user_element = "users";
5365 foreach ($members as $member) {
5366 $user = api_get_user($a, $member['nurl']);
5367 $users[$k++.":user"] = $user;
5370 $user_element = "user";
5371 foreach ($members as $member) {
5372 $user = api_get_user($a, $member['nurl']);
5376 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5378 return api_format_data("groups", $type, ['group' => $grps]);
5380 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5384 * Delete the specified group of the user.
5386 * @param string $type Return type (atom, rss, xml, json)
5388 * @return array|string
5390 function api_friendica_group_delete($type)
5394 if (api_user() === false) {
5395 throw new ForbiddenException();
5399 $user_info = api_get_user($a);
5400 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5401 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5402 $uid = $user_info['uid'];
5404 // error if no gid specified
5405 if ($gid == 0 || $name == "") {
5406 throw new BadRequestException('gid or name not specified');
5409 // get data of the specified group id
5411 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5415 // error message if specified gid is not in database
5416 if (!DBM::is_result($r)) {
5417 throw new BadRequestException('gid not available');
5420 // get data of the specified group id and group name
5422 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5427 // error message if specified gid is not in database
5428 if (!DBM::is_result($rname)) {
5429 throw new BadRequestException('wrong group name');
5433 $ret = Group::removeByName($uid, $name);
5436 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5437 return api_format_data("group_delete", $type, ['result' => $success]);
5439 throw new BadRequestException('other API error');
5442 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5447 * @param string $type Return type (atom, rss, xml, json)
5449 * @return array|string
5450 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5452 function api_lists_destroy($type)
5456 if (api_user() === false) {
5457 throw new ForbiddenException();
5461 $user_info = api_get_user($a);
5462 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5463 $uid = $user_info['uid'];
5465 // error if no gid specified
5467 throw new BadRequestException('gid not specified');
5470 // get data of the specified group id
5471 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5472 // error message if specified gid is not in database
5474 throw new BadRequestException('gid not available');
5477 if (Group::remove($gid)) {
5479 'name' => $group['name'],
5480 'id' => intval($gid),
5481 'id_str' => (string) $gid,
5482 'user' => $user_info
5485 return api_format_data("lists", $type, ['lists' => $list]);
5488 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5491 * Add a new group to the database.
5493 * @param string $name Group name
5494 * @param int $uid User ID
5495 * @param array $users List of users to add to the group
5499 function group_create($name, $uid, $users = [])
5501 // error if no name specified
5503 throw new BadRequestException('group name not specified');
5506 // get data of the specified group name
5508 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5512 // error message if specified group name already exists
5513 if (DBM::is_result($rname)) {
5514 throw new BadRequestException('group name already exists');
5517 // check if specified group name is a deleted group
5519 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5523 // error message if specified group name already exists
5524 if (DBM::is_result($rname)) {
5525 $reactivate_group = true;
5529 $ret = Group::create($uid, $name);
5531 $gid = Group::getIdByName($uid, $name);
5533 throw new BadRequestException('other API error');
5537 $erroraddinguser = false;
5539 foreach ($users as $user) {
5540 $cid = $user['cid'];
5541 // check if user really exists as contact
5543 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5547 if (count($contact)) {
5548 Group::addMember($gid, $cid);
5550 $erroraddinguser = true;
5551 $errorusers[] = $cid;
5555 // return success message incl. missing users in array
5556 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5558 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5562 * Create the specified group with the posted array of contacts.
5564 * @param string $type Return type (atom, rss, xml, json)
5566 * @return array|string
5568 function api_friendica_group_create($type)
5572 if (api_user() === false) {
5573 throw new ForbiddenException();
5577 $user_info = api_get_user($a);
5578 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5579 $uid = $user_info['uid'];
5580 $json = json_decode($_POST['json'], true);
5581 $users = $json['user'];
5583 $success = group_create($name, $uid, $users);
5585 return api_format_data("group_create", $type, ['result' => $success]);
5587 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5590 * Create a new group.
5592 * @param string $type Return type (atom, rss, xml, json)
5594 * @return array|string
5595 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5597 function api_lists_create($type)
5601 if (api_user() === false) {
5602 throw new ForbiddenException();
5606 $user_info = api_get_user($a);
5607 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5608 $uid = $user_info['uid'];
5610 $success = group_create($name, $uid);
5611 if ($success['success']) {
5613 'name' => $success['name'],
5614 'id' => intval($success['gid']),
5615 'id_str' => (string) $success['gid'],
5616 'user' => $user_info
5619 return api_format_data("lists", $type, ['lists'=>$grp]);
5622 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5625 * Update the specified group with the posted array of contacts.
5627 * @param string $type Return type (atom, rss, xml, json)
5629 * @return array|string
5631 function api_friendica_group_update($type)
5635 if (api_user() === false) {
5636 throw new ForbiddenException();
5640 $user_info = api_get_user($a);
5641 $uid = $user_info['uid'];
5642 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5643 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5644 $json = json_decode($_POST['json'], true);
5645 $users = $json['user'];
5647 // error if no name specified
5649 throw new BadRequestException('group name not specified');
5652 // error if no gid specified
5654 throw new BadRequestException('gid not specified');
5658 $members = Contact::getByGroupId($gid);
5659 foreach ($members as $member) {
5660 $cid = $member['id'];
5661 foreach ($users as $user) {
5662 $found = ($user['cid'] == $cid ? true : false);
5664 if (!isset($found) || !$found) {
5665 Group::removeMemberByName($uid, $name, $cid);
5670 $erroraddinguser = false;
5672 foreach ($users as $user) {
5673 $cid = $user['cid'];
5674 // check if user really exists as contact
5676 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5681 if (count($contact)) {
5682 Group::addMember($gid, $cid);
5684 $erroraddinguser = true;
5685 $errorusers[] = $cid;
5689 // return success message incl. missing users in array
5690 $status = ($erroraddinguser ? "missing user" : "ok");
5691 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5692 return api_format_data("group_update", $type, ['result' => $success]);
5695 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5698 * Update information about a group.
5700 * @param string $type Return type (atom, rss, xml, json)
5702 * @return array|string
5703 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5705 function api_lists_update($type)
5709 if (api_user() === false) {
5710 throw new ForbiddenException();
5714 $user_info = api_get_user($a);
5715 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5716 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5717 $uid = $user_info['uid'];
5719 // error if no gid specified
5721 throw new BadRequestException('gid not specified');
5724 // get data of the specified group id
5725 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5726 // error message if specified gid is not in database
5728 throw new BadRequestException('gid not available');
5731 if (Group::update($gid, $name)) {
5734 'id' => intval($gid),
5735 'id_str' => (string) $gid,
5736 'user' => $user_info
5739 return api_format_data("lists", $type, ['lists' => $list]);
5743 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5747 * @param string $type Return type (atom, rss, xml, json)
5749 * @return array|string
5751 function api_friendica_activity($type)
5755 if (api_user() === false) {
5756 throw new ForbiddenException();
5758 $verb = strtolower($a->argv[3]);
5759 $verb = preg_replace("|\..*$|", "", $verb);
5761 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5763 $res = Item::performLike($id, $verb);
5766 if ($type == "xml") {
5771 return api_format_data('ok', $type, ['ok' => $ok]);
5773 throw new BadRequestException('Error adding activity');
5777 /// @TODO move to top of file or somewhere better
5778 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5779 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5780 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5781 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5782 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5783 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5784 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5785 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5786 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5787 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5790 * @brief Returns notifications
5792 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5793 * @return string|array
5795 function api_friendica_notification($type)
5799 if (api_user() === false) {
5800 throw new ForbiddenException();
5803 throw new BadRequestException("Invalid argument count");
5805 $nm = new NotificationsManager();
5807 $notes = $nm->getAll([], "+seen -date", 50);
5809 if ($type == "xml") {
5811 foreach ($notes as $note) {
5812 $xmlnotes[] = ["@attributes" => $note];
5818 return api_format_data("notes", $type, ['note' => $notes]);
5822 * POST request with 'id' param as notification id
5824 * @brief Set notification as seen and returns associated item (if possible)
5826 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5827 * @return string|array
5829 function api_friendica_notification_seen($type)
5832 $user_info = api_get_user($a);
5834 if (api_user() === false || $user_info === false) {
5835 throw new ForbiddenException();
5838 throw new BadRequestException("Invalid argument count");
5841 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5843 $nm = new NotificationsManager();
5844 $note = $nm->getByID($id);
5845 if (is_null($note)) {
5846 throw new BadRequestException("Invalid argument");
5849 $nm->setSeen($note);
5850 if ($note['otype']=='item') {
5851 // would be really better with an ItemsManager and $im->getByID() :-P
5853 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5854 intval($note['iid']),
5855 intval(local_user())
5858 // we found the item, return it to the user
5859 $ret = api_format_items($r, $user_info, false, $type);
5860 $data = ['status' => $ret];
5861 return api_format_data("status", $type, $data);
5863 // the item can't be found, but we set the note as seen, so we count this as a success
5865 return api_format_data('result', $type, ['result' => "success"]);
5868 /// @TODO move to top of file or somewhere better
5869 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5870 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5873 * @brief update a direct_message to seen state
5875 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5876 * @return string|array (success result=ok, error result=error with error message)
5878 function api_friendica_direct_messages_setseen($type)
5881 if (api_user() === false) {
5882 throw new ForbiddenException();
5886 $user_info = api_get_user($a);
5887 $uid = $user_info['uid'];
5888 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5890 // return error if id is zero
5892 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5893 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5896 // error message if specified id is not in database
5897 if (!dba::exists('mail', ['id' => $id, 'uid' => $uid])) {
5898 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5899 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5902 // update seen indicator
5903 $result = dba::update('mail', ['seen' => true], ['id' => $id]);
5907 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5908 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5910 $answer = ['result' => 'error', 'message' => 'unknown error'];
5911 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5915 /// @TODO move to top of file or somewhere better
5916 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5919 * @brief search for direct_messages containing a searchstring through api
5921 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5922 * @param string $box
5923 * @return string|array (success: success=true if found and search_result contains found messages,
5924 * success=false if nothing was found, search_result='nothing found',
5925 * error: result=error with error message)
5927 function api_friendica_direct_messages_search($type, $box = "")
5931 if (api_user() === false) {
5932 throw new ForbiddenException();
5936 $user_info = api_get_user($a);
5937 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5938 $uid = $user_info['uid'];
5940 // error if no searchstring specified
5941 if ($searchstring == "") {
5942 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5943 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5946 // get data for the specified searchstring
5948 "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",
5950 dbesc('%'.$searchstring.'%')
5953 $profile_url = $user_info["url"];
5955 // message if nothing was found
5956 if (!DBM::is_result($r)) {
5957 $success = ['success' => false, 'search_results' => 'problem with query'];
5958 } elseif (count($r) == 0) {
5959 $success = ['success' => false, 'search_results' => 'nothing found'];
5962 foreach ($r as $item) {
5963 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5964 $recipient = $user_info;
5965 $sender = api_get_user($a, normalise_link($item['contact-url']));
5966 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5967 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5968 $sender = $user_info;
5971 if (isset($recipient) && isset($sender)) {
5972 $ret[] = api_format_messages($item, $recipient, $sender);
5975 $success = ['success' => true, 'search_results' => $ret];
5978 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5981 /// @TODO move to top of file or somewhere better
5982 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5985 * @brief return data of all the profiles a user has to the client
5987 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5988 * @return string|array
5990 function api_friendica_profile_show($type)
5994 if (api_user() === false) {
5995 throw new ForbiddenException();
5999 $profile_id = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
6001 // retrieve general information about profiles for user
6002 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6003 $directory = Config::get('system', 'directory');
6005 // get data of the specified profile id or all profiles of the user if not specified
6006 if ($profile_id != 0) {
6008 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
6013 // error message if specified gid is not in database
6014 if (!DBM::is_result($r)) {
6015 throw new BadRequestException("profile_id not available");
6019 "SELECT * FROM `profile` WHERE `uid` = %d",
6023 // loop through all returned profiles and retrieve data and users
6026 foreach ($r as $rr) {
6027 $profile = api_format_items_profiles($rr);
6029 // select all users from contact table, loop and prepare standard return for user data
6032 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
6034 intval($rr['profile_id'])
6037 foreach ($nurls as $nurl) {
6038 $user = api_get_user($a, $nurl['nurl']);
6039 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6041 $profile['users'] = $users;
6043 // add prepared profile data to array for final return
6044 if ($type == "xml") {
6045 $profiles[$k++ . ":profile"] = $profile;
6047 $profiles[] = $profile;
6051 // return settings, authenticated user and profiles data
6052 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
6054 $result = ['multi_profiles' => $multi_profiles ? true : false,
6055 'global_dir' => $directory,
6056 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
6057 'profiles' => $profiles];
6058 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6060 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6063 * Returns a list of saved searches.
6065 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6067 * @param string $type Return format: json or xml
6069 * @return string|array
6071 function api_saved_searches_list($type)
6073 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
6076 while ($term = $terms->fetch()) {
6078 'created_at' => api_date(time()),
6079 'id' => intval($term['id']),
6080 'id_str' => $term['id'],
6081 'name' => $term['term'],
6083 'query' => $term['term']
6089 return api_format_data("terms", $type, ['terms' => $result]);
6092 /// @TODO move to top of file or somewhere better
6093 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6096 @TODO Maybe open to implement?
6098 [pagename] => api/1.1/statuses/lookup.json
6099 [id] => 605138389168451584
6100 [include_cards] => true
6101 [cards_platform] => Android-12
6102 [include_entities] => true
6103 [include_my_retweet] => 1
6105 [include_reply_count] => true
6106 [include_descendent_reply_count] => true
6110 Not implemented by now:
6111 statuses/retweets_of_me
6116 account/update_location
6117 account/update_profile_background_image
6120 friendica/profile/update
6121 friendica/profile/create
6122 friendica/profile/delete
6124 Not implemented in status.net:
6125 statuses/retweeted_to_me
6126 statuses/retweeted_by_me
6127 direct_messages/destroy
6129 account/update_delivery_device
6130 notifications/follow