3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
9 use Friendica\Content\ContactSelector;
10 use Friendica\Content\Feature;
11 use Friendica\Content\Text\BBCode;
12 use Friendica\Core\Addon;
13 use Friendica\Core\System;
14 use Friendica\Core\Config;
15 use Friendica\Core\NotificationsManager;
16 use Friendica\Core\L10n;
17 use Friendica\Core\PConfig;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBM;
20 use Friendica\Model\Contact;
21 use Friendica\Model\Group;
22 use Friendica\Model\Mail;
23 use Friendica\Model\Photo;
24 use Friendica\Model\User;
25 use Friendica\Model\Item;
26 use Friendica\Network\FKOAuth1;
27 use Friendica\Network\HTTPException;
28 use Friendica\Network\HTTPException\BadRequestException;
29 use Friendica\Network\HTTPException\ForbiddenException;
30 use Friendica\Network\HTTPException\InternalServerErrorException;
31 use Friendica\Network\HTTPException\MethodNotAllowedException;
32 use Friendica\Network\HTTPException\NotFoundException;
33 use Friendica\Network\HTTPException\NotImplementedException;
34 use Friendica\Network\HTTPException\UnauthorizedException;
35 use Friendica\Network\HTTPException\TooManyRequestsException;
36 use Friendica\Object\Image;
37 use Friendica\Protocol\Diaspora;
38 use Friendica\Util\Network;
39 use Friendica\Util\XML;
41 require_once 'include/bbcode.php';
42 require_once 'include/datetime.php';
43 require_once 'include/conversation.php';
44 require_once 'include/html2plain.php';
45 require_once 'mod/share.php';
46 require_once 'mod/item.php';
47 require_once 'include/security.php';
48 require_once 'include/html2bbcode.php';
49 require_once 'mod/wall_upload.php';
50 require_once 'mod/proxy.php';
52 define('API_METHOD_ANY', '*');
53 define('API_METHOD_GET', 'GET');
54 define('API_METHOD_POST', 'POST,PUT');
55 define('API_METHOD_DELETE', 'POST,DELETE');
61 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
62 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
63 * into a page, and visitors will post something without noticing it).
65 * @brief Auth API user
69 if (x($_SESSION, 'allow_api')) {
77 * Clients can send 'source' parameter to be show in post metadata
78 * as "sent via <source>".
79 * Some clients doesn't send a source param, we support ones we know
82 * @brief Get source name from API client
85 * Client source name, default to "api" if unset/unknown
89 if (requestdata('source')) {
90 return requestdata('source');
93 // Support for known clients that doesn't send a source name
94 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
98 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
104 * @brief Format date for API
106 * @param string $str Source date, as UTC
107 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
109 function api_date($str)
111 // Wed May 23 06:01:13 +0000 2007
112 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y");
116 * Register a function to be the endpoint for defined API path.
118 * @brief Register API endpoint
120 * @param string $path API URL path, relative to System::baseUrl()
121 * @param string $func Function name to call on path request
122 * @param bool $auth API need logged user
123 * @param string $method HTTP method reqiured to call this endpoint.
124 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
125 * Default to API_METHOD_ANY
127 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
137 // Workaround for hotot
138 $path = str_replace("api/", "api/1.1/", $path);
148 * Log in user via OAuth1 or Simple HTTP Auth.
149 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
151 * @brief Login API user
153 * @param object $a App
154 * @hook 'authenticate'
156 * 'username' => username from login form
157 * 'password' => password from login form
158 * 'authenticated' => return status,
159 * 'user_record' => return authenticated user record
161 * array $user logged user record
163 function api_login(App $a)
165 $oauth1 = new FKOAuth1();
168 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
169 if (!is_null($token)) {
170 $oauth1->loginUser($token->uid);
171 Addon::callHooks('logged_in', $a->user);
174 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
175 var_dump($consumer, $token);
177 } catch (Exception $e) {
181 // workaround for HTTP-auth in CGI mode
182 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
183 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
184 if (strlen($userpass)) {
185 list($name, $password) = explode(':', $userpass);
186 $_SERVER['PHP_AUTH_USER'] = $name;
187 $_SERVER['PHP_AUTH_PW'] = $password;
191 if (!x($_SERVER, 'PHP_AUTH_USER')) {
192 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
193 header('WWW-Authenticate: Basic realm="Friendica"');
194 throw new UnauthorizedException("This API requires login");
197 $user = $_SERVER['PHP_AUTH_USER'];
198 $password = $_SERVER['PHP_AUTH_PW'];
200 // allow "user@server" login (but ignore 'server' part)
201 $at = strstr($user, "@", true);
206 // next code from mod/auth.php. needs better solution
210 'username' => trim($user),
211 'password' => trim($password),
212 'authenticated' => 0,
213 'user_record' => null,
217 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
218 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
219 * and later addons should not interfere with an earlier one that succeeded.
221 Addon::callHooks('authenticate', $addon_auth);
223 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
224 $record = $addon_auth['user_record'];
226 $user_id = User::authenticate(trim($user), trim($password));
228 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
232 if (!DBM::is_result($record)) {
233 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
234 header('WWW-Authenticate: Basic realm="Friendica"');
235 //header('HTTP/1.0 401 Unauthorized');
236 //die('This api requires login');
237 throw new UnauthorizedException("This API requires login");
240 authenticate_success($record);
242 $_SESSION["allow_api"] = true;
244 Addon::callHooks('logged_in', $a->user);
248 * API endpoints can define which HTTP method to accept when called.
249 * This function check the current HTTP method agains endpoint
252 * @brief Check HTTP method of called API
254 * @param string $method Required methods, uppercase, separated by comma
257 function api_check_method($method)
259 if ($method == "*") {
262 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
266 * Authenticate user, call registered API function, set HTTP headers
268 * @brief Main API entry point
270 * @param object $a App
271 * @return string API call result
273 function api_call(App $a)
275 global $API, $called_api;
278 if (strpos($a->query_string, ".xml") > 0) {
281 if (strpos($a->query_string, ".json") > 0) {
284 if (strpos($a->query_string, ".rss") > 0) {
287 if (strpos($a->query_string, ".atom") > 0) {
292 foreach ($API as $p => $info) {
293 if (strpos($a->query_string, $p) === 0) {
294 if (!api_check_method($info['method'])) {
295 throw new MethodNotAllowedException();
298 $called_api = explode("/", $p);
299 //unset($_SERVER['PHP_AUTH_USER']);
301 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
302 if ($info['auth'] === true && api_user() === false) {
306 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
307 logger('API parameters: ' . print_r($_REQUEST, true));
309 $stamp = microtime(true);
310 $return = call_user_func($info['func'], $type);
311 $duration = (float) (microtime(true) - $stamp);
312 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
314 if (Config::get("system", "profiler")) {
315 $duration = microtime(true)-$a->performance["start"];
317 /// @TODO round() really everywhere?
319 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
320 "Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
321 round($a->performance["database"] - $a->performance["database_write"], 3),
322 round($a->performance["database_write"], 3),
323 round($a->performance["network"], 2),
324 round($a->performance["file"], 2),
325 round($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
331 if (Config::get("rendertime", "callstack")) {
332 $o = "Database Read:\n";
333 foreach ($a->callstack["database"] as $func => $time) {
334 $time = round($time, 3);
336 $o .= $func . ": " . $time . "\n";
339 $o .= "\nDatabase Write:\n";
340 foreach ($a->callstack["database_write"] as $func => $time) {
341 $time = round($time, 3);
343 $o .= $func . ": " . $time . "\n";
347 $o .= "\nNetwork:\n";
348 foreach ($a->callstack["network"] as $func => $time) {
349 $time = round($time, 3);
351 $o .= $func . ": " . $time . "\n";
354 logger($o, LOGGER_DEBUG);
358 if (false === $return) {
360 * api function returned false withour throw an
361 * exception. This should not happend, throw a 500
363 throw new InternalServerErrorException();
368 header("Content-Type: text/xml");
371 header("Content-Type: application/json");
372 foreach ($return as $rr) {
373 $json = json_encode($rr);
375 if (x($_GET, 'callback')) {
376 $json = $_GET['callback'] . "(" . $json . ")";
381 header("Content-Type: application/rss+xml");
382 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
385 header("Content-Type: application/atom+xml");
386 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
393 logger('API call not implemented: ' . $a->query_string);
394 throw new NotImplementedException();
395 } catch (HTTPException $e) {
396 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
397 return api_error($type, $e);
402 * @brief Format API error string
404 * @param string $type Return type (xml, json, rss, as)
405 * @param object $e HTTPException Error object
406 * @return string error message formatted as $type
408 function api_error($type, $e)
412 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
413 /// @TODO: https://dev.twitter.com/overview/api/response-codes
415 $error = ["error" => $error,
416 "code" => $e->httpcode . " " . $e->httpdesc,
417 "request" => $a->query_string];
419 $return = api_format_data('status', $type, ['status' => $error]);
423 header("Content-Type: text/xml");
426 header("Content-Type: application/json");
427 $return = json_encode($return);
430 header("Content-Type: application/rss+xml");
433 header("Content-Type: application/atom+xml");
441 * @brief Set values for RSS template
444 * @param array $arr Array to be passed to template
445 * @param array $user_info User info
447 * @todo find proper type-hints
449 function api_rss_extra(App $a, $arr, $user_info)
451 if (is_null($user_info)) {
452 $user_info = api_get_user($a);
455 $arr['$user'] = $user_info;
457 'alternate' => $user_info['url'],
458 'self' => System::baseUrl() . "/" . $a->query_string,
459 'base' => System::baseUrl(),
460 'updated' => api_date(null),
461 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
462 'language' => $user_info['language'],
463 'logo' => System::baseUrl() . "/images/friendica-32.png",
471 * @brief Unique contact to contact url.
473 * @param int $id Contact id
474 * @return bool|string
475 * Contact url or False if contact id is unknown
477 function api_unique_id_to_nurl($id)
479 $r = dba::selectFirst('contact', ['nurl'], ['uid' => 0, 'id' => $id]);
481 if (DBM::is_result($r)) {
489 * @brief Get user info array.
491 * @param object $a App
492 * @param int|string $contact_id Contact ID or URL
494 function api_get_user(App $a, $contact_id = null)
502 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
504 // Searching for contact URL
505 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
506 $user = dbesc(normalise_link($contact_id));
508 $extra_query = "AND `contact`.`nurl` = '%s' ";
509 if (api_user() !== false) {
510 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
514 // Searching for contact id with uid = 0
515 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
516 $user = dbesc(api_unique_id_to_nurl($contact_id));
519 throw new BadRequestException("User not found.");
523 $extra_query = "AND `contact`.`nurl` = '%s' ";
524 if (api_user() !== false) {
525 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
529 if (is_null($user) && x($_GET, 'user_id')) {
530 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
533 throw new BadRequestException("User not found.");
537 $extra_query = "AND `contact`.`nurl` = '%s' ";
538 if (api_user() !== false) {
539 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
542 if (is_null($user) && x($_GET, 'screen_name')) {
543 $user = dbesc($_GET['screen_name']);
544 $extra_query = "AND `contact`.`nick` = '%s' ";
545 if (api_user() !== false) {
546 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
550 if (is_null($user) && x($_GET, 'profileurl')) {
551 $user = dbesc(normalise_link($_GET['profileurl']));
552 $extra_query = "AND `contact`.`nurl` = '%s' ";
553 if (api_user() !== false) {
554 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
558 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
559 $argid = count($called_api);
560 list($user, $null) = explode(".", $a->argv[$argid]);
561 if (is_numeric($user)) {
562 $user = dbesc(api_unique_id_to_nurl($user));
569 $extra_query = "AND `contact`.`nurl` = '%s' ";
570 if (api_user() !== false) {
571 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
574 $user = dbesc($user);
575 $extra_query = "AND `contact`.`nick` = '%s' ";
576 if (api_user() !== false) {
577 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
582 logger("api_get_user: user ".$user, LOGGER_DEBUG);
585 if (api_user() === false) {
589 $user = $_SESSION['uid'];
590 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
594 logger('api_user: ' . $extra_query . ', user: ' . $user);
598 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
604 // Selecting the id by priority, friendica first
605 api_best_nickname($uinfo);
607 // if the contact wasn't found, fetch it from the contacts with uid = 0
608 if (!DBM::is_result($uinfo)) {
612 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
615 if (DBM::is_result($r)) {
616 $network_name = ContactSelector::networkToName($r[0]['network'], $r[0]['url']);
618 // If no nick where given, extract it from the address
619 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
620 $r[0]['nick'] = api_get_nick($r[0]["url"]);
625 'id_str' => (string) $r[0]["id"],
626 'name' => $r[0]["name"],
627 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
628 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
629 'description' => $r[0]["about"],
630 'profile_image_url' => $r[0]["micro"],
631 'profile_image_url_https' => $r[0]["micro"],
632 'url' => $r[0]["url"],
633 'protected' => false,
634 'followers_count' => 0,
635 'friends_count' => 0,
637 'created_at' => api_date($r[0]["created"]),
638 'favourites_count' => 0,
640 'time_zone' => 'UTC',
641 'geo_enabled' => false,
643 'statuses_count' => 0,
645 'contributors_enabled' => false,
646 'is_translator' => false,
647 'is_translation_enabled' => false,
648 'following' => false,
649 'follow_request_sent' => false,
650 'statusnet_blocking' => false,
651 'notifications' => false,
652 'statusnet_profile_url' => $r[0]["url"],
654 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
656 'network' => $r[0]["network"],
661 throw new BadRequestException("User not found.");
665 if ($uinfo[0]['self']) {
666 if ($uinfo[0]['network'] == "") {
667 $uinfo[0]['network'] = NETWORK_DFRN;
671 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
675 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
679 /// @TODO old-lost code? (twice)
680 // Counting is deactivated by now, due to performance issues
681 // count public wall messages
682 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
683 // intval($uinfo[0]['uid'])
685 //$countitms = $r[0]['count'];
688 // Counting is deactivated by now, due to performance issues
689 //$r = q("SELECT count(*) as `count` FROM `item`
690 // WHERE `contact-id` = %d",
691 // intval($uinfo[0]['id'])
693 //$countitms = $r[0]['count'];
697 /// @TODO old-lost code? (twice)
699 // Counting is deactivated by now, due to performance issues
701 $r = q("SELECT count(*) as `count` FROM `contact`
702 WHERE `uid` = %d AND `rel` IN ( %d, %d )
703 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
704 intval($uinfo[0]['uid']),
705 intval(CONTACT_IS_SHARING),
706 intval(CONTACT_IS_FRIEND)
708 $countfriends = $r[0]['count'];
710 $r = q("SELECT count(*) as `count` FROM `contact`
711 WHERE `uid` = %d AND `rel` IN ( %d, %d )
712 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
713 intval($uinfo[0]['uid']),
714 intval(CONTACT_IS_FOLLOWER),
715 intval(CONTACT_IS_FRIEND)
717 $countfollowers = $r[0]['count'];
719 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
720 intval($uinfo[0]['uid'])
722 $starred = $r[0]['count'];
725 if (! $uinfo[0]['self']) {
735 // Add a nick if it isn't present there
736 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
737 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
740 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
742 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
744 if (!empty($profile[0]['about'])) {
745 $description = $profile[0]['about'];
747 $description = $uinfo[0]["about"];
750 if (!empty($usr[0]['default-location'])) {
751 $location = $usr[0]['default-location'];
752 } elseif (!empty($uinfo[0]["location"])) {
753 $location = $uinfo[0]["location"];
755 $location = $network_name;
759 'id' => intval($pcontact_id),
760 'id_str' => (string) intval($pcontact_id),
761 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
762 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
763 'location' => $location,
764 'description' => $description,
765 'profile_image_url' => $uinfo[0]['micro'],
766 'profile_image_url_https' => $uinfo[0]['micro'],
767 'url' => $uinfo[0]['url'],
768 'protected' => false,
769 'followers_count' => intval($countfollowers),
770 'friends_count' => intval($countfriends),
772 'created_at' => api_date($uinfo[0]['created']),
773 'favourites_count' => intval($starred),
775 'time_zone' => 'UTC',
776 'geo_enabled' => false,
778 'statuses_count' => intval($countitms),
780 'contributors_enabled' => false,
781 'is_translator' => false,
782 'is_translation_enabled' => false,
783 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
784 'follow_request_sent' => false,
785 'statusnet_blocking' => false,
786 'notifications' => false,
788 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
789 'statusnet_profile_url' => $uinfo[0]['url'],
790 'uid' => intval($uinfo[0]['uid']),
791 'cid' => intval($uinfo[0]['cid']),
792 'self' => $uinfo[0]['self'],
793 'network' => $uinfo[0]['network'],
796 // If this is a local user and it uses Frio, we can get its color preferences.
798 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
799 if ($theme_info['theme'] === 'frio') {
800 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
801 if ($schema && ($schema != '---')) {
802 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
803 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
804 require_once $schemefile;
807 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
808 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
809 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
815 $link_color = "#6fdbe8";
818 $bgcolor = "#ededed";
821 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
822 $ret['profile_link_color'] = str_replace('#', '', $link_color);
823 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
831 * @brief return api-formatted array for item's author and owner
833 * @param object $a App
834 * @param array $item item from db
835 * @return array(array:author, array:owner)
837 function api_item_get_user(App $a, $item)
839 $status_user = api_get_user($a, $item["author-link"]);
841 $status_user["protected"] = (($item["allow_cid"] != "") ||
842 ($item["allow_gid"] != "") ||
843 ($item["deny_cid"] != "") ||
844 ($item["deny_gid"] != "") ||
847 if ($item['thr-parent'] == $item['uri']) {
848 $owner_user = api_get_user($a, $item["owner-link"]);
850 $owner_user = $status_user;
853 return ([$status_user, $owner_user]);
857 * @brief walks recursively through an array with the possibility to change value and key
859 * @param array $array The array to walk through
860 * @param string $callback The callback function
862 * @return array the transformed array
864 function api_walk_recursive(array &$array, callable $callback)
868 foreach ($array as $k => $v) {
870 if ($callback($v, $k)) {
871 $new_array[$k] = api_walk_recursive($v, $callback);
874 if ($callback($v, $k)) {
885 * @brief Callback function to transform the array in an array that can be transformed in a XML file
887 * @param mixed $item Array item value
888 * @param string $key Array key
890 * @return boolean Should the array item be deleted?
892 function api_reformat_xml(&$item, &$key)
894 if (is_bool($item)) {
895 $item = ($item ? "true" : "false");
898 if (substr($key, 0, 10) == "statusnet_") {
899 $key = "statusnet:".substr($key, 10);
900 } elseif (substr($key, 0, 10) == "friendica_") {
901 $key = "friendica:".substr($key, 10);
903 /// @TODO old-lost code?
905 // $key = "default:".$key;
911 * @brief Creates the XML from a JSON style array
913 * @param array $data JSON style array
914 * @param string $root_element Name of the root element
916 * @return string The XML data
918 function api_create_xml($data, $root_element)
920 $childname = key($data);
921 $data2 = array_pop($data);
924 $namespaces = ["" => "http://api.twitter.com",
925 "statusnet" => "http://status.net/schema/api/1/",
926 "friendica" => "http://friendi.ca/schema/api/1/",
927 "georss" => "http://www.georss.org/georss"];
929 /// @todo Auto detection of needed namespaces
930 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
934 if (is_array($data2)) {
935 api_walk_recursive($data2, "api_reformat_xml");
942 foreach ($data2 as $item) {
943 $data4[$i++.":".$childname] = $item;
949 $data3 = [$root_element => $data2];
951 $ret = XML::fromArray($data3, $xml, false, $namespaces);
956 * @brief Formats the data according to the data type
958 * @param string $root_element Name of the root element
959 * @param string $type Return type (atom, rss, xml, json)
960 * @param array $data JSON style array
962 * @return (string|object|array) XML data or JSON data
964 function api_format_data($root_element, $type, $data)
970 $ret = api_create_xml($data, $root_element);
985 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
986 * returns a 401 status code and an error message if not.
987 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
989 * @param string $type Return type (atom, rss, xml, json)
991 function api_account_verify_credentials($type)
996 if (api_user() === false) {
997 throw new ForbiddenException();
1000 unset($_REQUEST["user_id"]);
1001 unset($_GET["user_id"]);
1003 unset($_REQUEST["screen_name"]);
1004 unset($_GET["screen_name"]);
1006 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1008 $user_info = api_get_user($a);
1010 // "verified" isn't used here in the standard
1011 unset($user_info["verified"]);
1013 // - Adding last status
1014 if (!$skip_status) {
1015 $user_info["status"] = api_status_show("raw");
1016 if (!count($user_info["status"])) {
1017 unset($user_info["status"]);
1019 unset($user_info["status"]["user"]);
1023 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1024 unset($user_info["uid"]);
1025 unset($user_info["self"]);
1027 return api_format_data("user", $type, ['user' => $user_info]);
1030 /// @TODO move to top of file or somewhere better
1031 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1034 * Get data from $_POST or $_GET
1038 function requestdata($k)
1040 if (x($_POST, $k)) {
1050 * Waitman Gobble Mod
1052 * @param string $type Return type (atom, rss, xml, json)
1054 * @return array|string
1056 function api_statuses_mediap($type)
1060 if (api_user() === false) {
1061 logger('api_statuses_update: no user');
1062 throw new ForbiddenException();
1064 $user_info = api_get_user($a);
1066 $_REQUEST['type'] = 'wall';
1067 $_REQUEST['profile_uid'] = api_user();
1068 $_REQUEST['api_source'] = true;
1069 $txt = requestdata('status');
1070 /// @TODO old-lost code?
1071 //$txt = urldecode(requestdata('status'));
1073 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1074 $txt = html2bb_video($txt);
1075 $config = HTMLPurifier_Config::createDefault();
1076 $config->set('Cache.DefinitionImpl', null);
1077 $purifier = new HTMLPurifier($config);
1078 $txt = $purifier->purify($txt);
1080 $txt = html2bbcode($txt);
1082 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1084 // tell wall_upload function to return img info instead of echo
1085 $_REQUEST['hush'] = 'yeah';
1086 $bebop = wall_upload_post($a);
1088 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1089 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1092 // this should output the last post (the one we just posted).
1093 return api_status_show($type);
1096 /// @TODO move this to top of file or somewhere better!
1097 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1100 * Updates the user’s current status.
1102 * @param string $type Return type (atom, rss, xml, json)
1104 * @return array|string
1105 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1107 function api_statuses_update($type)
1112 if (api_user() === false) {
1113 logger('api_statuses_update: no user');
1114 throw new ForbiddenException();
1119 // convert $_POST array items to the form we use for web posts.
1120 if (requestdata('htmlstatus')) {
1121 $txt = requestdata('htmlstatus');
1122 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1123 $txt = html2bb_video($txt);
1125 $config = HTMLPurifier_Config::createDefault();
1126 $config->set('Cache.DefinitionImpl', null);
1128 $purifier = new HTMLPurifier($config);
1129 $txt = $purifier->purify($txt);
1131 $_REQUEST['body'] = html2bbcode($txt);
1134 $_REQUEST['body'] = requestdata('status');
1137 $_REQUEST['title'] = requestdata('title');
1139 $parent = requestdata('in_reply_to_status_id');
1141 // Twidere sends "-1" if it is no reply ...
1142 if ($parent == -1) {
1146 if (ctype_digit($parent)) {
1147 $_REQUEST['parent'] = $parent;
1149 $_REQUEST['parent_uri'] = $parent;
1152 if (requestdata('lat') && requestdata('long')) {
1153 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1155 $_REQUEST['profile_uid'] = api_user();
1158 $_REQUEST['type'] = 'net-comment';
1160 // Check for throttling (maximum posts per day, week and month)
1161 $throttle_day = Config::get('system', 'throttle_limit_day');
1162 if ($throttle_day > 0) {
1163 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1166 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1167 AND `created` > '%s' AND `id` = `parent`",
1172 if (DBM::is_result($r)) {
1173 $posts_day = $r[0]["posts_day"];
1178 if ($posts_day > $throttle_day) {
1179 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1180 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1181 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));
1185 $throttle_week = Config::get('system', 'throttle_limit_week');
1186 if ($throttle_week > 0) {
1187 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1190 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1191 AND `created` > '%s' AND `id` = `parent`",
1196 if (DBM::is_result($r)) {
1197 $posts_week = $r[0]["posts_week"];
1202 if ($posts_week > $throttle_week) {
1203 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1204 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1205 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));
1209 $throttle_month = Config::get('system', 'throttle_limit_month');
1210 if ($throttle_month > 0) {
1211 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1214 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1215 AND `created` > '%s' AND `id` = `parent`",
1220 if (DBM::is_result($r)) {
1221 $posts_month = $r[0]["posts_month"];
1226 if ($posts_month > $throttle_month) {
1227 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1228 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1229 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));
1233 $_REQUEST['type'] = 'wall';
1236 if (x($_FILES, 'media')) {
1237 // upload the image if we have one
1238 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1239 $media = wall_upload_post($a);
1240 if (strlen($media) > 0) {
1241 $_REQUEST['body'] .= "\n\n" . $media;
1245 // To-Do: Multiple IDs
1246 if (requestdata('media_ids')) {
1248 "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",
1249 intval(requestdata('media_ids')),
1252 if (DBM::is_result($r)) {
1253 $phototypes = Image::supportedTypes();
1254 $ext = $phototypes[$r[0]['type']];
1255 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1256 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1260 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1262 $_REQUEST['api_source'] = true;
1264 if (!x($_REQUEST, "source")) {
1265 $_REQUEST["source"] = api_source();
1268 // call out normal post function
1271 // this should output the last post (the one we just posted).
1272 return api_status_show($type);
1275 /// @TODO move to top of file or somewhere better
1276 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1277 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1280 * Uploads an image to Friendica.
1283 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1285 function api_media_upload()
1289 if (api_user() === false) {
1291 throw new ForbiddenException();
1296 if (!x($_FILES, 'media')) {
1298 throw new BadRequestException("No media.");
1301 $media = wall_upload_post($a, false);
1304 throw new InternalServerErrorException();
1308 $returndata["media_id"] = $media["id"];
1309 $returndata["media_id_string"] = (string)$media["id"];
1310 $returndata["size"] = $media["size"];
1311 $returndata["image"] = ["w" => $media["width"],
1312 "h" => $media["height"],
1313 "image_type" => $media["type"]];
1315 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1317 return ["media" => $returndata];
1320 /// @TODO move to top of file or somewhere better
1321 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1325 * @param string $type Return type (atom, rss, xml, json)
1327 * @return array|string
1329 function api_status_show($type)
1333 $user_info = api_get_user($a);
1335 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1337 if ($type == "raw") {
1338 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1343 // get last public wall message
1347 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1348 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1349 AND `item`.`type` != 'activity' $privacy_sql
1350 ORDER BY `item`.`id` DESC
1352 intval($user_info['cid']),
1354 dbesc($user_info['url']),
1355 dbesc(normalise_link($user_info['url'])),
1356 dbesc($user_info['url']),
1357 dbesc(normalise_link($user_info['url']))
1360 if (DBM::is_result($lastwall)) {
1361 $lastwall = $lastwall[0];
1363 $in_reply_to = api_in_reply_to($lastwall);
1365 $converted = api_convert_item($lastwall);
1367 if ($type == "xml") {
1368 $geo = "georss:point";
1374 'created_at' => api_date($lastwall['created']),
1375 'id' => intval($lastwall['id']),
1376 'id_str' => (string) $lastwall['id'],
1377 'text' => $converted["text"],
1378 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1379 'truncated' => false,
1380 'in_reply_to_status_id' => $in_reply_to['status_id'],
1381 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1382 'in_reply_to_user_id' => $in_reply_to['user_id'],
1383 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1384 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1385 'user' => $user_info,
1387 'coordinates' => "",
1389 'contributors' => "",
1390 'is_quote_status' => false,
1391 'retweet_count' => 0,
1392 'favorite_count' => 0,
1393 'favorited' => $lastwall['starred'] ? true : false,
1394 'retweeted' => false,
1395 'possibly_sensitive' => false,
1397 'statusnet_html' => $converted["html"],
1398 'statusnet_conversation_id' => $lastwall['parent'],
1399 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1402 if (count($converted["attachments"]) > 0) {
1403 $status_info["attachments"] = $converted["attachments"];
1406 if (count($converted["entities"]) > 0) {
1407 $status_info["entities"] = $converted["entities"];
1410 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1411 $status_info["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1412 } elseif (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1413 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['item_network'], $user_info['url']).')');
1416 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1417 unset($status_info["user"]["uid"]);
1418 unset($status_info["user"]["self"]);
1421 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1423 if ($type == "raw") {
1424 return $status_info;
1427 return api_format_data("statuses", $type, ['status' => $status_info]);
1431 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1432 * The author's most recent status will be returned inline.
1434 * @param string $type Return type (atom, rss, xml, json)
1435 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1437 function api_users_show($type)
1441 $user_info = api_get_user($a);
1445 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1446 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1447 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1448 AND `type`!='activity'
1449 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1453 dbesc(ACTIVITY_POST),
1454 intval($user_info['cid']),
1455 dbesc($user_info['url']),
1456 dbesc(normalise_link($user_info['url'])),
1457 dbesc($user_info['url']),
1458 dbesc(normalise_link($user_info['url']))
1461 if (DBM::is_result($lastwall)) {
1462 $lastwall = $lastwall[0];
1464 $in_reply_to = api_in_reply_to($lastwall);
1466 $converted = api_convert_item($lastwall);
1468 if ($type == "xml") {
1469 $geo = "georss:point";
1474 $user_info['status'] = [
1475 'text' => $converted["text"],
1476 'truncated' => false,
1477 'created_at' => api_date($lastwall['created']),
1478 'in_reply_to_status_id' => $in_reply_to['status_id'],
1479 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1480 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1481 'id' => intval($lastwall['contact-id']),
1482 'id_str' => (string) $lastwall['contact-id'],
1483 'in_reply_to_user_id' => $in_reply_to['user_id'],
1484 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1485 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1487 'favorited' => $lastwall['starred'] ? true : false,
1488 'statusnet_html' => $converted["html"],
1489 'statusnet_conversation_id' => $lastwall['parent'],
1490 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1493 if (count($converted["attachments"]) > 0) {
1494 $user_info["status"]["attachments"] = $converted["attachments"];
1497 if (count($converted["entities"]) > 0) {
1498 $user_info["status"]["entities"] = $converted["entities"];
1501 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1502 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1505 if (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1506 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) . ')');
1510 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1511 unset($user_info["uid"]);
1512 unset($user_info["self"]);
1514 return api_format_data("user", $type, ['user' => $user_info]);
1517 /// @TODO move to top of file or somewhere better
1518 api_register_func('api/users/show', 'api_users_show');
1519 api_register_func('api/externalprofile/show', 'api_users_show');
1522 * Search a public user account.
1524 * @param string $type Return type (atom, rss, xml, json)
1526 * @return array|string
1527 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1529 function api_users_search($type)
1535 if (x($_GET, 'q')) {
1536 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1538 if (!DBM::is_result($r)) {
1539 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1542 if (DBM::is_result($r)) {
1544 foreach ($r as $user) {
1545 $user_info = api_get_user($a, $user["id"]);
1547 if ($type == "xml") {
1548 $userlist[$k++.":user"] = $user_info;
1550 $userlist[] = $user_info;
1553 $userlist = ["users" => $userlist];
1555 throw new BadRequestException("User not found.");
1558 throw new BadRequestException("User not found.");
1561 return api_format_data("users", $type, $userlist);
1564 /// @TODO move to top of file or somewhere better
1565 api_register_func('api/users/search', 'api_users_search');
1568 * Return user objects
1570 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1572 * @param string $type Return format: json or xml
1574 * @return array|string
1575 * @throws NotFoundException if the results are empty.
1577 function api_users_lookup($type)
1581 if (x($_REQUEST['user_id'])) {
1582 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1584 $users[] = api_get_user(get_app(), $id);
1589 if (empty($users)) {
1590 throw new NotFoundException;
1593 return api_format_data("users", $type, ['users' => $users]);
1596 /// @TODO move to top of file or somewhere better
1597 api_register_func('api/users/lookup', 'api_users_lookup', true);
1600 * Returns statuses that match a specified query.
1602 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1604 * @param string $type Return format: json, xml, atom, rss
1606 * @return array|string
1607 * @throws BadRequestException if the "q" parameter is missing.
1609 function api_search($type)
1613 if (!x($_REQUEST, 'q')) {
1614 throw new BadRequestException("q parameter is required.");
1617 if (x($_REQUEST, 'rpp')) {
1618 $count = $_REQUEST['rpp'];
1619 } elseif (x($_REQUEST, 'count')) {
1620 $count = $_REQUEST['count'];
1625 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1626 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1627 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1629 $start = $page * $count;
1632 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1636 "SELECT ".item_fieldlists()."
1637 FROM `item` ".item_joins()."
1638 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1639 AND `item`.`body` LIKE CONCAT('%',?,'%')
1642 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1648 $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1650 return api_format_data("statuses", $type, $data);
1653 /// @TODO move to top of file or somewhere better
1654 api_register_func('api/search/tweets', 'api_search', true);
1655 api_register_func('api/search', 'api_search', true);
1658 * Returns the most recent statuses posted by the user and the users they follow.
1660 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1662 * @param string $type Return type (atom, rss, xml, json)
1664 * @todo Optional parameters
1665 * @todo Add reply info
1667 function api_statuses_home_timeline($type)
1671 if (api_user() === false) {
1672 throw new ForbiddenException();
1675 unset($_REQUEST["user_id"]);
1676 unset($_GET["user_id"]);
1678 unset($_REQUEST["screen_name"]);
1679 unset($_GET["screen_name"]);
1681 $user_info = api_get_user($a);
1682 // get last newtork messages
1685 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1686 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1690 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1691 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1692 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1693 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1694 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1696 $start = $page * $count;
1700 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1702 if ($exclude_replies > 0) {
1703 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1705 if ($conversation_id > 0) {
1706 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1710 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1711 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1712 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1713 `contact`.`id` AS `cid`
1715 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1716 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1717 WHERE `item`.`uid` = %d AND `verb` = '%s'
1718 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1721 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1723 dbesc(ACTIVITY_POST),
1729 $ret = api_format_items($r, $user_info, false, $type);
1731 // Set all posts from the query above to seen
1733 foreach ($r as $item) {
1734 $idarray[] = intval($item["id"]);
1737 $idlist = implode(",", $idarray);
1739 if ($idlist != "") {
1740 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1743 q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1747 $data = ['status' => $ret];
1751 $data = api_rss_extra($a, $data, $user_info);
1755 return api_format_data("statuses", $type, $data);
1758 /// @TODO move to top of file or somewhere better
1759 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1760 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1763 * Returns the most recent statuses from public users.
1765 * @param string $type Return type (atom, rss, xml, json)
1767 * @return array|string
1769 function api_statuses_public_timeline($type)
1773 if (api_user() === false) {
1774 throw new ForbiddenException();
1777 $user_info = api_get_user($a);
1778 // get last newtork messages
1781 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1782 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1786 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1787 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1788 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1789 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1790 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1792 $start = $page * $count;
1794 if ($exclude_replies && !$conversation_id) {
1796 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1800 "SELECT " . item_fieldlists() . "
1802 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1803 " . item_joins() . "
1804 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1805 AND NOT `user`.`hidewall`
1807 AND NOT `thread`.`private`
1809 AND `thread`.`visible`
1810 AND NOT `thread`.`deleted`
1811 AND NOT `thread`.`moderated`
1812 AND `thread`.`iid` > ?
1814 ORDER BY `thread`.`iid` DESC
1815 LIMIT " . intval($start) . ", " . intval($count),
1820 $r = dba::inArray($r);
1823 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1825 if ($conversation_id > 0) {
1826 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1830 "SELECT " . item_fieldlists() . "
1832 " . item_joins() . "
1833 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1834 AND NOT `user`.`hidewall`
1836 AND NOT `item`.`private`
1838 AND `item`.`visible`
1839 AND NOT `item`.`deleted`
1840 AND NOT `item`.`moderated`
1843 ORDER BY `item`.`id` DESC
1844 LIMIT " . intval($start) . ", " . intval($count),
1849 $r = dba::inArray($r);
1852 $ret = api_format_items($r, $user_info, false, $type);
1854 $data = ['status' => $ret];
1858 $data = api_rss_extra($a, $data, $user_info);
1862 return api_format_data("statuses", $type, $data);
1865 /// @TODO move to top of file or somewhere better
1866 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1869 * Returns the most recent statuses posted by users this node knows about.
1871 * @brief Returns the list of public federated posts this node knows about
1873 * @param string $type Return format: json, xml, atom, rss
1874 * @return array|string
1875 * @throws ForbiddenException
1877 function api_statuses_networkpublic_timeline($type)
1881 if (api_user() === false) {
1882 throw new ForbiddenException();
1885 $user_info = api_get_user($a);
1887 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1888 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1891 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1892 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1896 $start = ($page - 1) * $count;
1900 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1904 "SELECT " . item_fieldlists() . "
1906 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1907 " . item_joins() . "
1908 WHERE `thread`.`uid` = 0
1910 AND NOT `thread`.`private`
1911 AND `thread`.`visible`
1912 AND NOT `thread`.`deleted`
1913 AND NOT `thread`.`moderated`
1914 AND `thread`.`iid` > ?
1916 ORDER BY `thread`.`iid` DESC
1917 LIMIT " . intval($start) . ", " . intval($count),
1922 $r = dba::inArray($r);
1924 $ret = api_format_items($r, $user_info, false, $type);
1926 $data = ['status' => $ret];
1930 $data = api_rss_extra($a, $data, $user_info);
1934 return api_format_data("statuses", $type, $data);
1937 /// @TODO move to top of file or somewhere better
1938 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1941 * Returns a single status.
1943 * @param string $type Return type (atom, rss, xml, json)
1945 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1947 function api_statuses_show($type)
1951 if (api_user() === false) {
1952 throw new ForbiddenException();
1955 $user_info = api_get_user($a);
1958 $id = intval($a->argv[3]);
1961 $id = intval($_REQUEST["id"]);
1966 $id = intval($a->argv[4]);
1969 logger('API: api_statuses_show: ' . $id);
1971 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1974 if ($conversation) {
1975 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1977 $sql_extra .= " AND `item`.`id` = %d";
1981 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1982 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1983 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1984 `contact`.`id` AS `cid`
1986 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1987 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1988 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1989 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1992 dbesc(ACTIVITY_POST),
1996 /// @TODO How about copying this to above methods which don't check $r ?
1997 if (!DBM::is_result($r)) {
1998 throw new BadRequestException("There is no status with this id.");
2001 $ret = api_format_items($r, $user_info, false, $type);
2003 if ($conversation) {
2004 $data = ['status' => $ret];
2005 return api_format_data("statuses", $type, $data);
2007 $data = ['status' => $ret[0]];
2008 return api_format_data("status", $type, $data);
2012 /// @TODO move to top of file or somewhere better
2013 api_register_func('api/statuses/show', 'api_statuses_show', true);
2017 * @param string $type Return type (atom, rss, xml, json)
2019 * @todo nothing to say?
2021 function api_conversation_show($type)
2025 if (api_user() === false) {
2026 throw new ForbiddenException();
2029 $user_info = api_get_user($a);
2032 $id = intval($a->argv[3]);
2033 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2034 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
2038 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2039 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2041 $start = $page*$count;
2044 $id = intval($_REQUEST["id"]);
2049 $id = intval($a->argv[4]);
2052 logger('API: api_conversation_show: '.$id);
2054 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
2055 if (DBM::is_result($r)) {
2056 $id = $r[0]["parent"];
2062 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2065 // Not sure why this query was so complicated. We should keep it here for a while,
2066 // just to make sure that we really don't need it.
2067 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2068 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2071 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2072 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2073 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2074 `contact`.`id` AS `cid`
2076 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2077 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2078 WHERE `item`.`parent` = %d AND `item`.`visible`
2079 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2080 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2081 AND `item`.`id`>%d $sql_extra
2082 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2085 dbesc(ACTIVITY_POST),
2091 if (!DBM::is_result($r)) {
2092 throw new BadRequestException("There is no status with this id.");
2095 $ret = api_format_items($r, $user_info, false, $type);
2097 $data = ['status' => $ret];
2098 return api_format_data("statuses", $type, $data);
2101 /// @TODO move to top of file or somewhere better
2102 api_register_func('api/conversation/show', 'api_conversation_show', true);
2103 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2108 * @param string $type Return type (atom, rss, xml, json)
2110 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2112 function api_statuses_repeat($type)
2118 if (api_user() === false) {
2119 throw new ForbiddenException();
2125 $id = intval($a->argv[3]);
2128 $id = intval($_REQUEST["id"]);
2133 $id = intval($a->argv[4]);
2136 logger('API: api_statuses_repeat: '.$id);
2139 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2140 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2141 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2142 `contact`.`id` AS `cid`
2144 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2145 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2146 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2147 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2148 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2150 AND `item`.`id`=%d",
2154 /// @TODO other style than above functions!
2155 if (DBM::is_result($r) && $r[0]['body'] != "") {
2156 if (strpos($r[0]['body'], "[/share]") !== false) {
2157 $pos = strpos($r[0]['body'], "[share");
2158 $post = substr($r[0]['body'], $pos);
2160 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2162 $post .= $r[0]['body'];
2163 $post .= "[/share]";
2165 $_REQUEST['body'] = $post;
2166 $_REQUEST['profile_uid'] = api_user();
2167 $_REQUEST['type'] = 'wall';
2168 $_REQUEST['api_source'] = true;
2170 if (!x($_REQUEST, "source")) {
2171 $_REQUEST["source"] = api_source();
2176 throw new ForbiddenException();
2179 // this should output the last post (the one we just posted).
2181 return api_status_show($type);
2184 /// @TODO move to top of file or somewhere better
2185 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2188 * Destroys a specific status.
2190 * @param string $type Return type (atom, rss, xml, json)
2192 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2194 function api_statuses_destroy($type)
2198 if (api_user() === false) {
2199 throw new ForbiddenException();
2205 $id = intval($a->argv[3]);
2208 $id = intval($_REQUEST["id"]);
2213 $id = intval($a->argv[4]);
2216 logger('API: api_statuses_destroy: '.$id);
2218 $ret = api_statuses_show($type);
2225 /// @TODO move to top of file or somewhere better
2226 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2229 * Returns the most recent mentions.
2231 * @param string $type Return type (atom, rss, xml, json)
2233 * @see http://developer.twitter.com/doc/get/statuses/mentions
2235 function api_statuses_mentions($type)
2239 if (api_user() === false) {
2240 throw new ForbiddenException();
2243 unset($_REQUEST["user_id"]);
2244 unset($_GET["user_id"]);
2246 unset($_REQUEST["screen_name"]);
2247 unset($_GET["screen_name"]);
2249 $user_info = api_get_user($a);
2250 // get last newtork messages
2254 $since_id = defaults($_REQUEST, 'since_id', 0);
2255 $max_id = defaults($_REQUEST, 'max_id' , 0);
2256 $count = defaults($_REQUEST, 'count' , 20);
2257 $page = defaults($_REQUEST, 'page' , 1);
2262 $start = ($page - 1) * $count;
2264 // Ugly code - should be changed
2265 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2266 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2267 $myurl = str_replace('www.', '', $myurl);
2270 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2274 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2275 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2276 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2277 `contact`.`id` AS `cid`
2278 FROM `item` FORCE INDEX (`uid_id`)
2279 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2280 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2281 WHERE `item`.`uid` = %d AND `verb` = '%s'
2282 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2283 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2284 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2287 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2289 dbesc(ACTIVITY_POST),
2290 dbesc(protect_sprintf($myurl)),
2291 dbesc(protect_sprintf($myurl)),
2298 $ret = api_format_items($r, $user_info, false, $type);
2300 $data = ['status' => $ret];
2304 $data = api_rss_extra($a, $data, $user_info);
2308 return api_format_data("statuses", $type, $data);
2311 /// @TODO move to top of file or somewhere better
2312 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2313 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2316 * Returns the most recent statuses posted by the user.
2318 * @brief Returns a user's public timeline
2320 * @param string $type Either "json" or "xml"
2321 * @return string|array
2322 * @throws ForbiddenException
2323 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2325 function api_statuses_user_timeline($type)
2329 if (api_user() === false) {
2330 throw new ForbiddenException();
2333 $user_info = api_get_user($a);
2336 "api_statuses_user_timeline: api_user: ". api_user() .
2337 "\nuser_info: ".print_r($user_info, true) .
2338 "\n_REQUEST: ".print_r($_REQUEST, true),
2342 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2343 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2344 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2345 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2348 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2349 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2353 $start = ($page - 1) * $count;
2356 if ($user_info['self'] == 1) {
2357 $sql_extra .= " AND `item`.`wall` = 1 ";
2360 if ($exclude_replies > 0) {
2361 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2364 if ($conversation_id > 0) {
2365 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2369 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2373 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2374 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2375 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2376 `contact`.`id` AS `cid`
2377 FROM `item` FORCE INDEX (`uid_contactid_id`)
2378 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2379 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2380 WHERE `item`.`uid` = %d AND `verb` = '%s'
2381 AND `item`.`contact-id` = %d
2382 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2384 AND `item`.`id` > %d
2385 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2387 dbesc(ACTIVITY_POST),
2388 intval($user_info['cid']),
2394 $ret = api_format_items($r, $user_info, true, $type);
2396 $data = ['status' => $ret];
2400 $data = api_rss_extra($a, $data, $user_info);
2404 return api_format_data("statuses", $type, $data);
2407 /// @TODO move to top of file or somewhere better
2408 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2411 * Star/unstar an item.
2412 * param: id : id of the item
2414 * @param string $type Return type (atom, rss, xml, json)
2416 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2418 function api_favorites_create_destroy($type)
2422 if (api_user() === false) {
2423 throw new ForbiddenException();
2426 // for versioned api.
2427 /// @TODO We need a better global soluton
2428 $action_argv_id = 2;
2429 if ($a->argv[1] == "1.1") {
2430 $action_argv_id = 3;
2433 if ($a->argc <= $action_argv_id) {
2434 throw new BadRequestException("Invalid request.");
2436 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2437 if ($a->argc == $action_argv_id + 2) {
2438 $itemid = intval($a->argv[$action_argv_id + 1]);
2440 /// @TODO use x() to check if _REQUEST contains 'id'
2441 $itemid = intval($_REQUEST['id']);
2444 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2446 if (!DBM::is_result($item) || count($item) == 0) {
2447 throw new BadRequestException("Invalid item.");
2452 $item[0]['starred'] = 1;
2455 $item[0]['starred'] = 0;
2458 throw new BadRequestException("Invalid action ".$action);
2461 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2463 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2466 throw new InternalServerErrorException("DB error");
2470 $user_info = api_get_user($a);
2471 $rets = api_format_items($item, $user_info, false, $type);
2474 $data = ['status' => $ret];
2478 $data = api_rss_extra($a, $data, $user_info);
2481 return api_format_data("status", $type, $data);
2484 /// @TODO move to top of file or somewhere better
2485 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2486 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2489 * Returns the most recent favorite statuses.
2491 * @param string $type Return type (atom, rss, xml, json)
2493 * @return string|array
2495 function api_favorites($type)
2501 if (api_user() === false) {
2502 throw new ForbiddenException();
2507 $user_info = api_get_user($a);
2509 // in friendica starred item are private
2510 // return favorites only for self
2511 logger('api_favorites: self:' . $user_info['self']);
2513 if ($user_info['self'] == 0) {
2519 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2520 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2521 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2522 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2527 $start = $page*$count;
2530 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2534 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2535 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2536 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2537 `contact`.`id` AS `cid`
2538 FROM `item`, `contact`
2539 WHERE `item`.`uid` = %d
2540 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2541 AND `item`.`starred` = 1
2542 AND `contact`.`id` = `item`.`contact-id`
2543 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2546 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2553 $ret = api_format_items($r, $user_info, false, $type);
2556 $data = ['status' => $ret];
2560 $data = api_rss_extra($a, $data, $user_info);
2563 return api_format_data("statuses", $type, $data);
2566 /// @TODO move to top of file or somewhere better
2567 api_register_func('api/favorites', 'api_favorites', true);
2571 * @param array $item
2572 * @param array $recipient
2573 * @param array $sender
2577 function api_format_messages($item, $recipient, $sender)
2579 // standard meta information
2581 'id' => $item['id'],
2582 'sender_id' => $sender['id'] ,
2584 'recipient_id' => $recipient['id'],
2585 'created_at' => api_date($item['created']),
2586 'sender_screen_name' => $sender['screen_name'],
2587 'recipient_screen_name' => $recipient['screen_name'],
2588 'sender' => $sender,
2589 'recipient' => $recipient,
2591 'friendica_seen' => $item['seen'],
2592 'friendica_parent_uri' => $item['parent-uri'],
2595 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2596 unset($ret["sender"]["uid"]);
2597 unset($ret["sender"]["self"]);
2598 unset($ret["recipient"]["uid"]);
2599 unset($ret["recipient"]["self"]);
2601 //don't send title to regular StatusNET requests to avoid confusing these apps
2602 if (x($_GET, 'getText')) {
2603 $ret['title'] = $item['title'];
2604 if ($_GET['getText'] == 'html') {
2605 $ret['text'] = bbcode($item['body'], false, false);
2606 } elseif ($_GET['getText'] == 'plain') {
2607 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2608 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2611 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2613 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2614 unset($ret['sender']);
2615 unset($ret['recipient']);
2623 * @param array $item
2627 function api_convert_item($item)
2629 $body = $item['body'];
2630 $attachments = api_get_attachments($body);
2632 // Workaround for ostatus messages where the title is identically to the body
2633 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2634 $statusbody = trim(html2plain($html, 0));
2636 // handle data: images
2637 $statusbody = api_format_items_embeded_images($item, $statusbody);
2639 $statustitle = trim($item['title']);
2641 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2642 $statustext = trim($statusbody);
2644 $statustext = trim($statustitle."\n\n".$statusbody);
2647 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2648 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2651 $statushtml = trim(bbcode($body, false, false));
2653 // Workaround for clients with limited HTML parser functionality
2654 $search = ["<br>", "<blockquote>", "</blockquote>",
2655 "<h1>", "</h1>", "<h2>", "</h2>",
2656 "<h3>", "</h3>", "<h4>", "</h4>",
2657 "<h5>", "</h5>", "<h6>", "</h6>"];
2658 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2659 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2660 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2661 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2662 $statushtml = str_replace($search, $replace, $statushtml);
2664 if ($item['title'] != "") {
2665 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2669 $oldtext = $statushtml;
2670 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2671 } while ($oldtext != $statushtml);
2673 if (substr($statushtml, 0, 4) == '<br>') {
2674 $statushtml = substr($statushtml, 4);
2677 if (substr($statushtml, 0, -4) == '<br>') {
2678 $statushtml = substr($statushtml, -4);
2681 // feeds without body should contain the link
2682 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2683 $statushtml .= bbcode($item['plink']);
2686 $entities = api_get_entitities($statustext, $body);
2689 "text" => $statustext,
2690 "html" => $statushtml,
2691 "attachments" => $attachments,
2692 "entities" => $entities
2698 * @param string $body
2700 * @return array|false
2702 function api_get_attachments(&$body)
2705 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2707 $URLSearchString = "^\[\]";
2708 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2716 foreach ($images[1] as $image) {
2717 $imagedata = Image::getInfoFromURL($image);
2720 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2724 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2725 foreach ($images[0] as $orig) {
2726 $body = str_replace($orig, "", $body);
2730 return $attachments;
2735 * @param string $text
2736 * @param string $bbcode
2739 * @todo Links at the first character of the post
2741 function api_get_entitities(&$text, $bbcode)
2743 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2745 if ($include_entities != "true") {
2746 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2748 foreach ($images[1] as $image) {
2749 $replace = proxy_url($image);
2750 $text = str_replace($image, $replace, $text);
2755 $bbcode = bb_CleanPictureLinks($bbcode);
2757 // Change pure links in text to bbcode uris
2758 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2761 $entities["hashtags"] = [];
2762 $entities["symbols"] = [];
2763 $entities["urls"] = [];
2764 $entities["user_mentions"] = [];
2766 $URLSearchString = "^\[\]";
2768 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2770 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2771 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2772 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2774 $bbcode = preg_replace(
2775 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2776 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2779 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2781 $bbcode = preg_replace(
2782 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2783 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2786 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2788 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2790 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2791 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2794 foreach ($urls[1] as $id => $url) {
2795 //$start = strpos($text, $url, $offset);
2796 $start = iconv_strpos($text, $url, 0, "UTF-8");
2797 if (!($start === false)) {
2798 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2802 ksort($ordered_urls);
2805 //foreach ($urls[1] AS $id=>$url) {
2806 foreach ($ordered_urls as $url) {
2807 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2808 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2810 $display_url = $url["title"];
2812 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2813 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2815 if (strlen($display_url) > 26) {
2816 $display_url = substr($display_url, 0, 25)."…";
2820 //$start = strpos($text, $url, $offset);
2821 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2822 if (!($start === false)) {
2823 $entities["urls"][] = ["url" => $url["url"],
2824 "expanded_url" => $url["url"],
2825 "display_url" => $display_url,
2826 "indices" => [$start, $start+strlen($url["url"])]];
2827 $offset = $start + 1;
2831 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2832 $ordered_images = [];
2833 foreach ($images[1] as $image) {
2834 //$start = strpos($text, $url, $offset);
2835 $start = iconv_strpos($text, $image, 0, "UTF-8");
2836 if (!($start === false)) {
2837 $ordered_images[$start] = $image;
2840 //$entities["media"] = array();
2843 foreach ($ordered_images as $url) {
2844 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2845 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2847 if (strlen($display_url) > 26) {
2848 $display_url = substr($display_url, 0, 25)."…";
2851 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2852 if (!($start === false)) {
2853 $image = Image::getInfoFromURL($url);
2855 // If image cache is activated, then use the following sizes:
2856 // thumb (150), small (340), medium (600) and large (1024)
2857 if (!Config::get("system", "proxy_disabled")) {
2858 $media_url = proxy_url($url);
2861 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2862 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2864 if (($image[0] > 150) || ($image[1] > 150)) {
2865 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2866 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2869 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2870 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2872 if (($image[0] > 600) || ($image[1] > 600)) {
2873 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2874 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2878 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2881 $entities["media"][] = [
2883 "id_str" => (string)$start+1,
2884 "indices" => [$start, $start+strlen($url)],
2885 "media_url" => normalise_link($media_url),
2886 "media_url_https" => $media_url,
2888 "display_url" => $display_url,
2889 "expanded_url" => $url,
2893 $offset = $start + 1;
2902 * @param array $item
2903 * @param string $text
2907 function api_format_items_embeded_images($item, $text)
2909 $text = preg_replace_callback(
2910 '|data:image/([^;]+)[^=]+=*|m',
2911 function () use ($item) {
2912 return System::baseUrl() . '/display/' . $item['guid'];
2920 * @brief return <a href='url'>name</a> as array
2922 * @param string $txt text
2927 function api_contactlink_to_array($txt)
2930 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2931 if ($r && count($match)==3) {
2933 'name' => $match[2],
2947 * @brief return likes, dislikes and attend status for item
2949 * @param array $item array
2950 * @param string $type Return type (atom, rss, xml, json)
2953 * likes => int count,
2954 * dislikes => int count
2956 function api_format_items_activities(&$item, $type = "json")
2965 'attendmaybe' => [],
2970 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2971 intval($item['uid']),
2975 foreach ($items as $i) {
2976 // not used as result should be structured like other user data
2977 //builtin_activity_puller($i, $activities);
2979 // get user data and add it to the array of the activity
2980 $user = api_get_user($a, $i['author-link']);
2981 switch ($i['verb']) {
2983 $activities['like'][] = $user;
2985 case ACTIVITY_DISLIKE:
2986 $activities['dislike'][] = $user;
2988 case ACTIVITY_ATTEND:
2989 $activities['attendyes'][] = $user;
2991 case ACTIVITY_ATTENDNO:
2992 $activities['attendno'][] = $user;
2994 case ACTIVITY_ATTENDMAYBE:
2995 $activities['attendmaybe'][] = $user;
3002 if ($type == "xml") {
3003 $xml_activities = [];
3004 foreach ($activities as $k => $v) {
3005 // change xml element from "like" to "friendica:like"
3006 $xml_activities["friendica:".$k] = $v;
3007 // add user data into xml output
3009 foreach ($v as $user) {
3010 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
3013 $activities = $xml_activities;
3021 * @brief return data from profiles
3023 * @param array $profile_row array containing data from db table 'profile'
3026 function api_format_items_profiles($profile_row)
3029 'profile_id' => $profile_row['id'],
3030 'profile_name' => $profile_row['profile-name'],
3031 'is_default' => $profile_row['is-default'] ? true : false,
3032 'hide_friends' => $profile_row['hide-friends'] ? true : false,
3033 'profile_photo' => $profile_row['photo'],
3034 'profile_thumb' => $profile_row['thumb'],
3035 'publish' => $profile_row['publish'] ? true : false,
3036 'net_publish' => $profile_row['net-publish'] ? true : false,
3037 'description' => $profile_row['pdesc'],
3038 'date_of_birth' => $profile_row['dob'],
3039 'address' => $profile_row['address'],
3040 'city' => $profile_row['locality'],
3041 'region' => $profile_row['region'],
3042 'postal_code' => $profile_row['postal-code'],
3043 'country' => $profile_row['country-name'],
3044 'hometown' => $profile_row['hometown'],
3045 'gender' => $profile_row['gender'],
3046 'marital' => $profile_row['marital'],
3047 'marital_with' => $profile_row['with'],
3048 'marital_since' => $profile_row['howlong'],
3049 'sexual' => $profile_row['sexual'],
3050 'politic' => $profile_row['politic'],
3051 'religion' => $profile_row['religion'],
3052 'public_keywords' => $profile_row['pub_keywords'],
3053 'private_keywords' => $profile_row['prv_keywords'],
3054 'likes' => bbcode(api_clean_plain_items($profile_row['likes']) , false, false, 2, false),
3055 'dislikes' => bbcode(api_clean_plain_items($profile_row['dislikes']) , false, false, 2, false),
3056 'about' => bbcode(api_clean_plain_items($profile_row['about']) , false, false, 2, false),
3057 'music' => bbcode(api_clean_plain_items($profile_row['music']) , false, false, 2, false),
3058 'book' => bbcode(api_clean_plain_items($profile_row['book']) , false, false, 2, false),
3059 'tv' => bbcode(api_clean_plain_items($profile_row['tv']) , false, false, 2, false),
3060 'film' => bbcode(api_clean_plain_items($profile_row['film']) , false, false, 2, false),
3061 'interest' => bbcode(api_clean_plain_items($profile_row['interest']) , false, false, 2, false),
3062 'romance' => bbcode(api_clean_plain_items($profile_row['romance']) , false, false, 2, false),
3063 'work' => bbcode(api_clean_plain_items($profile_row['work']) , false, false, 2, false),
3064 'education' => bbcode(api_clean_plain_items($profile_row['education']), false, false, 2, false),
3065 'social_networks' => bbcode(api_clean_plain_items($profile_row['contact']) , false, false, 2, false),
3066 'homepage' => $profile_row['homepage'],
3073 * @brief format items to be returned by api
3075 * @param array $r array of items
3076 * @param array $user_info
3077 * @param bool $filter_user filter items by $user_info
3078 * @param string $type Return type (atom, rss, xml, json)
3080 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3086 foreach ($r as $item) {
3087 localize_item($item);
3088 list($status_user, $owner_user) = api_item_get_user($a, $item);
3090 // Look if the posts are matching if they should be filtered by user id
3091 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3095 $in_reply_to = api_in_reply_to($item);
3097 $converted = api_convert_item($item);
3099 if ($type == "xml") {
3100 $geo = "georss:point";
3106 'text' => $converted["text"],
3107 'truncated' => false,
3108 'created_at'=> api_date($item['created']),
3109 'in_reply_to_status_id' => $in_reply_to['status_id'],
3110 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3111 'source' => (($item['app']) ? $item['app'] : 'web'),
3112 'id' => intval($item['id']),
3113 'id_str' => (string) intval($item['id']),
3114 'in_reply_to_user_id' => $in_reply_to['user_id'],
3115 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3116 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3118 'favorited' => $item['starred'] ? true : false,
3119 'user' => $status_user ,
3120 'friendica_owner' => $owner_user,
3121 //'entities' => NULL,
3122 'statusnet_html' => $converted["html"],
3123 'statusnet_conversation_id' => $item['parent'],
3124 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3125 'friendica_activities' => api_format_items_activities($item, $type),
3128 if (count($converted["attachments"]) > 0) {
3129 $status["attachments"] = $converted["attachments"];
3132 if (count($converted["entities"]) > 0) {
3133 $status["entities"] = $converted["entities"];
3136 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3137 $status["source"] = ContactSelector::networkToName($item['item_network'], $user_info['url']);
3138 } elseif (($item['item_network'] != "") && (ContactSelector::networkToName($item['item_network'], $user_info['url']) != $status["source"])) {
3139 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['item_network'], $user_info['url']).')');
3143 // Retweets are only valid for top postings
3144 // It doesn't work reliable with the link if its a feed
3145 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3147 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3150 if ($item["id"] == $item["parent"]) {
3151 $retweeted_item = api_share_as_retweet($item);
3152 if ($retweeted_item !== false) {
3153 $retweeted_status = $status;
3155 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3156 } catch (BadRequestException $e) {
3157 // user not found. should be found?
3158 /// @todo check if the user should be always found
3159 $retweeted_status["user"] = [];
3162 $rt_converted = api_convert_item($retweeted_item);
3164 $retweeted_status['text'] = $rt_converted["text"];
3165 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3166 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3167 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3168 $status['retweeted_status'] = $retweeted_status;
3172 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3173 unset($status["user"]["uid"]);
3174 unset($status["user"]["self"]);
3176 if ($item["coord"] != "") {
3177 $coords = explode(' ', $item["coord"]);
3178 if (count($coords) == 2) {
3179 if ($type == "json") {
3180 $status["geo"] = ['type' => 'Point',
3181 'coordinates' => [(float) $coords[0],
3182 (float) $coords[1]]];
3183 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3184 $status["georss:point"] = $item["coord"];
3194 * Returns the remaining number of API requests available to the user before the API limit is reached.
3196 * @param string $type Return type (atom, rss, xml, json)
3198 * @return array|string
3200 function api_account_rate_limit_status($type)
3202 if ($type == "xml") {
3204 'remaining-hits' => '150',
3205 '@attributes' => ["type" => "integer"],
3206 'hourly-limit' => '150',
3207 '@attributes2' => ["type" => "integer"],
3208 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
3209 '@attributes3' => ["type" => "datetime"],
3210 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3211 '@attributes4' => ["type" => "integer"],
3215 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3216 'remaining_hits' => '150',
3217 'hourly_limit' => '150',
3218 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
3222 return api_format_data('hash', $type, ['hash' => $hash]);
3225 /// @TODO move to top of file or somewhere better
3226 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3229 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3231 * @param string $type Return type (atom, rss, xml, json)
3233 * @return array|string
3235 function api_help_test($type)
3237 if ($type == 'xml') {
3243 return api_format_data('ok', $type, ["ok" => $ok]);
3246 /// @TODO move to top of file or somewhere better
3247 api_register_func('api/help/test', 'api_help_test', false);
3251 * @param string $type Return type (atom, rss, xml, json)
3253 * @return array|string
3255 function api_lists($type)
3258 /// @TODO $ret is not filled here?
3259 return api_format_data('lists', $type, ["lists_list" => $ret]);
3262 /// @TODO move to top of file or somewhere better
3263 api_register_func('api/lists', 'api_lists', true);
3266 * Returns all lists the user subscribes to.
3268 * @param string $type Return type (atom, rss, xml, json)
3270 * @return array|string
3271 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3273 function api_lists_list($type)
3276 /// @TODO $ret is not filled here?
3277 return api_format_data('lists', $type, ["lists_list" => $ret]);
3280 /// @TODO move to top of file or somewhere better
3281 api_register_func('api/lists/list', 'api_lists_list', true);
3284 * Considers friends and followers lists to be private and won't return
3285 * anything if any user_id parameter is passed.
3287 * @brief Returns either the friends of the follower list
3289 * @param string $qtype Either "friends" or "followers"
3290 * @return boolean|array
3291 * @throws ForbiddenException
3293 function api_statuses_f($qtype)
3297 if (api_user() === false) {
3298 throw new ForbiddenException();
3302 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3303 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3307 $start = ($page - 1) * $count;
3309 $user_info = api_get_user($a);
3311 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3312 /* this is to stop Hotot to load friends multiple times
3313 * I'm not sure if I'm missing return something or
3314 * is a bug in hotot. Workaround, meantime
3318 return array('$users' => $ret);*/
3323 if ($qtype == 'friends') {
3324 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3325 } elseif ($qtype == 'followers') {
3326 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3329 // friends and followers only for self
3330 if ($user_info['self'] == 0) {
3331 $sql_extra = " AND false ";
3334 if ($qtype == 'blocks') {
3335 $sql_filter = 'AND `blocked` AND NOT `pending`';
3336 } elseif ($qtype == 'incoming') {
3337 $sql_filter = 'AND `pending`';
3339 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3357 foreach ($r as $cid) {
3358 $user = api_get_user($a, $cid['nurl']);
3359 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3360 unset($user["uid"]);
3361 unset($user["self"]);
3368 return ['user' => $ret];
3373 * Returns the user's friends.
3375 * @brief Returns the list of friends of the provided user
3377 * @deprecated By Twitter API in favor of friends/list
3379 * @param string $type Either "json" or "xml"
3380 * @return boolean|string|array
3382 function api_statuses_friends($type)
3384 $data = api_statuses_f("friends");
3385 if ($data === false) {
3388 return api_format_data("users", $type, $data);
3392 * Returns the user's followers.
3394 * @brief Returns the list of followers of the provided user
3396 * @deprecated By Twitter API in favor of friends/list
3398 * @param string $type Either "json" or "xml"
3399 * @return boolean|string|array
3401 function api_statuses_followers($type)
3403 $data = api_statuses_f("followers");
3404 if ($data === false) {
3407 return api_format_data("users", $type, $data);
3410 /// @TODO move to top of file or somewhere better
3411 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3412 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3415 * Returns the list of blocked users
3417 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3419 * @param string $type Either "json" or "xml"
3421 * @return boolean|string|array
3423 function api_blocks_list($type)
3425 $data = api_statuses_f('blocks');
3426 if ($data === false) {
3429 return api_format_data("users", $type, $data);
3432 /// @TODO move to top of file or somewhere better
3433 api_register_func('api/blocks/list', 'api_blocks_list', true);
3436 * Returns the list of pending users IDs
3438 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3440 * @param string $type Either "json" or "xml"
3442 * @return boolean|string|array
3444 function api_friendships_incoming($type)
3446 $data = api_statuses_f('incoming');
3447 if ($data === false) {
3452 foreach ($data['user'] as $user) {
3453 $ids[] = $user['id'];
3456 return api_format_data("ids", $type, ['id' => $ids]);
3459 /// @TODO move to top of file or somewhere better
3460 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3463 * Returns the instance's configuration information.
3465 * @param string $type Return type (atom, rss, xml, json)
3467 * @return array|string
3469 function api_statusnet_config($type)
3473 $name = $a->config['sitename'];
3474 $server = $a->get_hostname();
3475 $logo = System::baseUrl() . '/images/friendica-64.png';
3476 $email = $a->config['admin_email'];
3477 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3478 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3479 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3480 if ($a->config['api_import_size']) {
3481 $textlimit = (string) $a->config['api_import_size'];
3483 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3484 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3487 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3488 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3489 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3490 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3491 'shorturllength' => '30',
3493 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3494 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3495 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3496 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3501 return api_format_data('config', $type, ['config' => $config]);
3504 /// @TODO move to top of file or somewhere better
3505 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3506 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3510 * @param string $type Return type (atom, rss, xml, json)
3512 * @return array|string
3514 function api_statusnet_version($type)
3517 $fake_statusnet_version = "0.9.7";
3519 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3522 /// @TODO move to top of file or somewhere better
3523 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3524 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3528 * @param string $type Return type (atom, rss, xml, json)
3530 * @todo use api_format_data() to return data
3532 function api_ff_ids($type)
3535 throw new ForbiddenException();
3540 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3543 "SELECT `pcontact`.`id` FROM `contact`
3544 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3545 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3548 if (!DBM::is_result($r)) {
3553 foreach ($r as $rr) {
3554 if ($stringify_ids) {
3557 $ids[] = intval($rr['id']);
3561 return api_format_data("ids", $type, ['id' => $ids]);
3565 * Returns the ID of every user the user is following.
3567 * @param string $type Return type (atom, rss, xml, json)
3569 * @return array|string
3570 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3572 function api_friends_ids($type)
3574 return api_ff_ids($type);
3578 * Returns the ID of every user following the user.
3580 * @param string $type Return type (atom, rss, xml, json)
3582 * @return array|string
3583 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3585 function api_followers_ids($type)
3587 return api_ff_ids($type);
3590 /// @TODO move to top of file or somewhere better
3591 api_register_func('api/friends/ids', 'api_friends_ids', true);
3592 api_register_func('api/followers/ids', 'api_followers_ids', true);
3595 * Sends a new direct message.
3597 * @param string $type Return type (atom, rss, xml, json)
3599 * @return array|string
3600 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3602 function api_direct_messages_new($type)
3607 if (api_user() === false) {
3608 throw new ForbiddenException();
3611 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3615 $sender = api_get_user($a);
3617 if ($_POST['screen_name']) {
3619 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3621 dbesc($_POST['screen_name'])
3624 // Selecting the id by priority, friendica first
3625 api_best_nickname($r);
3627 $recipient = api_get_user($a, $r[0]['nurl']);
3629 $recipient = api_get_user($a, $_POST['user_id']);
3634 if (x($_REQUEST, 'replyto')) {
3636 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3638 intval($_REQUEST['replyto'])
3640 $replyto = $r[0]['parent-uri'];
3641 $sub = $r[0]['title'];
3643 if (x($_REQUEST, 'title')) {
3644 $sub = $_REQUEST['title'];
3646 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3650 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3653 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3654 $ret = api_format_messages($r[0], $recipient, $sender);
3656 $ret = ["error"=>$id];
3659 $data = ['direct_message'=>$ret];
3664 $data = api_rss_extra($a, $data, $user_info);
3667 return api_format_data("direct-messages", $type, $data);
3670 /// @TODO move to top of file or somewhere better
3671 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3674 * Destroys a direct message.
3676 * @brief delete a direct_message from mail table through api
3678 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3680 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3682 function api_direct_messages_destroy($type)
3686 if (api_user() === false) {
3687 throw new ForbiddenException();
3691 $user_info = api_get_user($a);
3693 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3695 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3696 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3697 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3699 $uid = $user_info['uid'];
3700 // error if no id or parenturi specified (for clients posting parent-uri as well)
3701 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3702 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3703 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3706 // BadRequestException if no id specified (for clients using Twitter API)
3708 throw new BadRequestException('Message id not specified');
3711 // add parent-uri to sql command if specified by calling app
3712 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3714 // get data of the specified message id
3716 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3721 // error message if specified id is not in database
3722 if (!DBM::is_result($r)) {
3723 if ($verbose == "true") {
3724 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3725 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3727 /// @todo BadRequestException ok for Twitter API clients?
3728 throw new BadRequestException('message id not in database');
3733 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3738 if ($verbose == "true") {
3741 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3742 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3744 $answer = ['result' => 'error', 'message' => 'unknown error'];
3745 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3748 /// @todo return JSON data like Twitter API not yet implemented
3751 /// @TODO move to top of file or somewhere better
3752 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3756 * @param string $type Return type (atom, rss, xml, json)
3757 * @param string $box
3758 * @param string $verbose
3760 * @return array|string
3762 function api_direct_messages_box($type, $box, $verbose)
3766 if (api_user() === false) {
3767 throw new ForbiddenException();
3771 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3772 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3777 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3778 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3780 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3781 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3784 unset($_REQUEST["user_id"]);
3785 unset($_GET["user_id"]);
3787 unset($_REQUEST["screen_name"]);
3788 unset($_GET["screen_name"]);
3790 $user_info = api_get_user($a);
3791 $profile_url = $user_info["url"];
3794 $start = $page * $count;
3797 if ($box=="sentbox") {
3798 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3799 } elseif ($box == "conversation") {
3800 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3801 } elseif ($box == "all") {
3802 $sql_extra = "true";
3803 } elseif ($box == "inbox") {
3804 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3808 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3811 if ($user_id != "") {
3812 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3813 } elseif ($screen_name !="") {
3814 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3818 "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",
3824 if ($verbose == "true" && !DBM::is_result($r)) {
3825 $answer = ['result' => 'error', 'message' => 'no mails available'];
3826 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3830 foreach ($r as $item) {
3831 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3832 $recipient = $user_info;
3833 $sender = api_get_user($a, normalise_link($item['contact-url']));
3834 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3835 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3836 $sender = $user_info;
3839 $ret[] = api_format_messages($item, $recipient, $sender);
3843 $data = ['direct_message' => $ret];
3847 $data = api_rss_extra($a, $data, $user_info);
3850 return api_format_data("direct-messages", $type, $data);
3854 * Returns the most recent direct messages sent by the user.
3856 * @param string $type Return type (atom, rss, xml, json)
3858 * @return array|string
3859 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3861 function api_direct_messages_sentbox($type)
3863 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3864 return api_direct_messages_box($type, "sentbox", $verbose);
3868 * Returns the most recent direct messages sent to the user.
3870 * @param string $type Return type (atom, rss, xml, json)
3872 * @return array|string
3873 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3875 function api_direct_messages_inbox($type)
3877 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3878 return api_direct_messages_box($type, "inbox", $verbose);
3883 * @param string $type Return type (atom, rss, xml, json)
3885 * @return array|string
3887 function api_direct_messages_all($type)
3889 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3890 return api_direct_messages_box($type, "all", $verbose);
3895 * @param string $type Return type (atom, rss, xml, json)
3897 * @return array|string
3899 function api_direct_messages_conversation($type)
3901 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3902 return api_direct_messages_box($type, "conversation", $verbose);
3905 /// @TODO move to top of file or somewhere better
3906 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3907 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3908 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3909 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3912 * Returns an OAuth Request Token.
3914 * @see https://oauth.net/core/1.0/#auth_step1
3916 function api_oauth_request_token()
3918 $oauth1 = new FKOAuth1();
3920 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3921 } catch (Exception $e) {
3922 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3930 * Returns an OAuth Access Token.
3932 * @return array|string
3933 * @see https://oauth.net/core/1.0/#auth_step3
3935 function api_oauth_access_token()
3937 $oauth1 = new FKOAuth1();
3939 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3940 } catch (Exception $e) {
3941 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3948 /// @TODO move to top of file or somewhere better
3949 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3950 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3954 * @brief delete a complete photoalbum with all containing photos from database through api
3956 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3959 function api_fr_photoalbum_delete($type)
3961 if (api_user() === false) {
3962 throw new ForbiddenException();
3965 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3967 // we do not allow calls without album string
3969 throw new BadRequestException("no albumname specified");
3971 // check if album is existing
3973 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3977 if (!DBM::is_result($r)) {
3978 throw new BadRequestException("album not available");
3981 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3982 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3983 foreach ($r as $rr) {
3985 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3986 intval(local_user()),
3987 dbesc($rr['resource-id'])
3990 if (!DBM::is_result($photo_item)) {
3991 throw new InternalServerErrorException("problem with deleting items occured");
3993 Item::delete($photo_item[0]['id']);
3996 // now let's delete all photos from the album
3997 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
3999 // return success of deletion or error message
4001 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4002 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4004 throw new InternalServerErrorException("unknown error - deleting from database failed");
4009 * @brief update the name of the album for all photos of an album
4011 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4014 function api_fr_photoalbum_update($type)
4016 if (api_user() === false) {
4017 throw new ForbiddenException();
4020 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4021 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4023 // we do not allow calls without album string
4025 throw new BadRequestException("no albumname specified");
4027 if ($album_new == "") {
4028 throw new BadRequestException("no new albumname specified");
4030 // check if album is existing
4032 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4036 if (!DBM::is_result($r)) {
4037 throw new BadRequestException("album not available");
4039 // now let's update all photos to the albumname
4041 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
4047 // return success of updating or error message
4049 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4050 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4052 throw new InternalServerErrorException("unknown error - updating in database failed");
4058 * @brief list all photos of the authenticated user
4060 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4063 function api_fr_photos_list($type)
4065 if (api_user() === false) {
4066 throw new ForbiddenException();
4069 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4070 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4071 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4072 intval(local_user())
4075 'image/jpeg' => 'jpg',
4076 'image/png' => 'png',
4077 'image/gif' => 'gif'
4079 $data = ['photo'=>[]];
4080 if (DBM::is_result($r)) {
4081 foreach ($r as $rr) {
4083 $photo['id'] = $rr['resource-id'];
4084 $photo['album'] = $rr['album'];
4085 $photo['filename'] = $rr['filename'];
4086 $photo['type'] = $rr['type'];
4087 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4088 $photo['created'] = $rr['created'];
4089 $photo['edited'] = $rr['edited'];
4090 $photo['desc'] = $rr['desc'];
4092 if ($type == "xml") {
4093 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4095 $photo['thumb'] = $thumb;
4096 $data['photo'][] = $photo;
4100 return api_format_data("photos", $type, $data);
4104 * @brief upload a new photo or change an existing photo
4106 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4109 function api_fr_photo_create_update($type)
4111 if (api_user() === false) {
4112 throw new ForbiddenException();
4115 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4116 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4117 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4118 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4119 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4120 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4121 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4122 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4123 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4125 // do several checks on input parameters
4126 // we do not allow calls without album string
4127 if ($album == null) {
4128 throw new BadRequestException("no albumname specified");
4130 // if photo_id == null --> we are uploading a new photo
4131 if ($photo_id == null) {
4134 // error if no media posted in create-mode
4135 if (!x($_FILES, 'media')) {
4137 throw new BadRequestException("no media data submitted");
4140 // album_new will be ignored in create-mode
4145 // check if photo is existing in database
4147 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4152 if (!DBM::is_result($r)) {
4153 throw new BadRequestException("photo not available");
4157 // checks on acl strings provided by clients
4158 $acl_input_error = false;
4159 $acl_input_error |= check_acl_input($allow_cid);
4160 $acl_input_error |= check_acl_input($deny_cid);
4161 $acl_input_error |= check_acl_input($allow_gid);
4162 $acl_input_error |= check_acl_input($deny_gid);
4163 if ($acl_input_error) {
4164 throw new BadRequestException("acl data invalid");
4166 // now let's upload the new media in create-mode
4167 if ($mode == "create") {
4168 $media = $_FILES['media'];
4169 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4171 // return success of updating or error message
4172 if (!is_null($data)) {
4173 return api_format_data("photo_create", $type, $data);
4175 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4179 // now let's do the changes in update-mode
4180 if ($mode == "update") {
4183 if (!is_null($desc)) {
4184 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4187 if (!is_null($album_new)) {
4188 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4191 if (!is_null($allow_cid)) {
4192 $allow_cid = trim($allow_cid);
4193 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4196 if (!is_null($deny_cid)) {
4197 $deny_cid = trim($deny_cid);
4198 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4201 if (!is_null($allow_gid)) {
4202 $allow_gid = trim($allow_gid);
4203 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4206 if (!is_null($deny_gid)) {
4207 $deny_gid = trim($deny_gid);
4208 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4212 if ($sql_extra != "") {
4213 $nothingtodo = false;
4215 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4217 datetime_convert(), // update edited timestamp
4223 $nothingtodo = true;
4226 if (x($_FILES, 'media')) {
4227 $nothingtodo = false;
4228 $media = $_FILES['media'];
4229 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4230 if (!is_null($data)) {
4231 return api_format_data("photo_update", $type, $data);
4235 // return success of updating or error message
4237 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4238 return api_format_data("photo_update", $type, ['$result' => $answer]);
4241 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4242 return api_format_data("photo_update", $type, ['$result' => $answer]);
4244 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4247 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4252 * @brief delete a single photo from the database through api
4254 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4257 function api_fr_photo_delete($type)
4259 if (api_user() === false) {
4260 throw new ForbiddenException();
4263 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4265 // do several checks on input parameters
4266 // we do not allow calls without photo id
4267 if ($photo_id == null) {
4268 throw new BadRequestException("no photo_id specified");
4270 // check if photo is existing in database
4272 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4276 if (!DBM::is_result($r)) {
4277 throw new BadRequestException("photo not available");
4279 // now we can perform on the deletion of the photo
4280 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4282 // return success of deletion or error message
4284 // retrieve the id of the parent element (the photo element)
4286 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4287 intval(local_user()),
4291 if (!DBM::is_result($photo_item)) {
4292 throw new InternalServerErrorException("problem with deleting items occured");
4294 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4295 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4296 Item::delete($photo_item[0]['id']);
4298 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4299 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4301 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4307 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4309 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4310 * @return string|array
4312 function api_fr_photo_detail($type)
4314 if (api_user() === false) {
4315 throw new ForbiddenException();
4317 if (!x($_REQUEST, 'photo_id')) {
4318 throw new BadRequestException("No photo id.");
4321 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4322 $photo_id = $_REQUEST['photo_id'];
4324 // prepare json/xml output with data from database for the requested photo
4325 $data = prepare_photo_data($type, $scale, $photo_id);
4327 return api_format_data("photo_detail", $type, $data);
4332 * Updates the user’s profile image.
4334 * @brief updates the profile image for the user (either a specified profile or the default profile)
4336 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4339 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4341 function api_account_update_profile_image($type)
4343 if (api_user() === false) {
4344 throw new ForbiddenException();
4347 $profileid = defaults($_REQUEST, 'profile_id', 0);
4349 // error if image data is missing
4350 if (!x($_FILES, 'image')) {
4351 throw new BadRequestException("no media data submitted");
4354 // check if specified profile id is valid
4355 if ($profileid != 0) {
4357 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4361 // error message if specified profile id is not in database
4362 if (!DBM::is_result($r)) {
4363 throw new BadRequestException("profile_id not available");
4365 $is_default_profile = $r['profile'];
4367 $is_default_profile = 1;
4370 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4372 if (x($_FILES, 'image')) {
4373 $media = $_FILES['image'];
4374 } elseif (x($_FILES, 'media')) {
4375 $media = $_FILES['media'];
4377 // save new profile image
4378 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4381 if (is_array($media['type'])) {
4382 $filetype = $media['type'][0];
4384 $filetype = $media['type'];
4386 if ($filetype == "image/jpeg") {
4388 } elseif ($filetype == "image/png") {
4391 // change specified profile or all profiles to the new resource-id
4392 if ($is_default_profile) {
4394 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4395 dbesc($data['photo']['id']),
4396 intval(local_user())
4400 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4401 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4402 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4403 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4404 intval(local_user())
4408 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4409 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4410 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4411 intval($_REQUEST['profile']),
4412 intval(local_user())
4416 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4417 // so that browsers will do a cache update unconditionally
4420 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4421 dbesc(datetime_convert()),
4422 intval(local_user())
4425 // Update global directory in background
4426 //$user = api_get_user(get_app());
4427 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4428 if ($url && strlen(Config::get('system', 'directory'))) {
4429 Worker::add(PRIORITY_LOW, "Directory", $url);
4432 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4434 // output for client
4436 return api_account_verify_credentials($type);
4438 // SaveMediaToDatabase failed for some reason
4439 throw new InternalServerErrorException("image upload failed");
4443 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4444 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4445 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4446 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4447 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4448 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4449 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4450 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4451 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4454 * Update user profile
4456 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4458 * @return array|string
4460 function api_account_update_profile($type)
4462 $local_user = api_user();
4463 $api_user = api_get_user(get_app());
4465 if (!empty($_POST['name'])) {
4466 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4467 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4468 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4469 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4472 if (isset($_POST['description'])) {
4473 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4474 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4475 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4478 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4479 // Update global directory in background
4480 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4481 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4484 return api_account_verify_credentials($type);
4487 /// @TODO move to top of file or somewhere better
4488 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4492 * @param string $acl_string
4494 function check_acl_input($acl_string)
4496 if ($acl_string == null || $acl_string == " ") {
4499 $contact_not_found = false;
4501 // split <x><y><z> into array of cid's
4502 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4504 // check for each cid if it is available on server
4505 $cid_array = $array[0];
4506 foreach ($cid_array as $cid) {
4507 $cid = str_replace("<", "", $cid);
4508 $cid = str_replace(">", "", $cid);
4510 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4514 $contact_not_found |= !DBM::is_result($contact);
4516 return $contact_not_found;
4521 * @param string $mediatype
4522 * @param array $media
4523 * @param string $type
4524 * @param string $album
4525 * @param string $allow_cid
4526 * @param string $deny_cid
4527 * @param string $allow_gid
4528 * @param string $deny_gid
4529 * @param string $desc
4530 * @param integer $profile
4531 * @param boolean $visibility
4532 * @param string $photo_id
4534 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)
4542 if (is_array($media)) {
4543 if (is_array($media['tmp_name'])) {
4544 $src = $media['tmp_name'][0];
4546 $src = $media['tmp_name'];
4548 if (is_array($media['name'])) {
4549 $filename = basename($media['name'][0]);
4551 $filename = basename($media['name']);
4553 if (is_array($media['size'])) {
4554 $filesize = intval($media['size'][0]);
4556 $filesize = intval($media['size']);
4558 if (is_array($media['type'])) {
4559 $filetype = $media['type'][0];
4561 $filetype = $media['type'];
4565 if ($filetype == "") {
4566 $filetype=Image::guessType($filename);
4568 $imagedata = getimagesize($src);
4570 $filetype = $imagedata['mime'];
4573 "File upload src: " . $src . " - filename: " . $filename .
4574 " - size: " . $filesize . " - type: " . $filetype,
4578 // check if there was a php upload error
4579 if ($filesize == 0 && $media['error'] == 1) {
4580 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4582 // check against max upload size within Friendica instance
4583 $maximagesize = Config::get('system', 'maximagesize');
4584 if ($maximagesize && ($filesize > $maximagesize)) {
4585 $formattedBytes = formatBytes($maximagesize);
4586 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4589 // create Photo instance with the data of the image
4590 $imagedata = @file_get_contents($src);
4591 $Image = new Image($imagedata, $filetype);
4592 if (! $Image->isValid()) {
4593 throw new InternalServerErrorException("unable to process image data");
4596 // check orientation of image
4597 $Image->orient($src);
4600 // check max length of images on server
4601 $max_length = Config::get('system', 'max_image_length');
4602 if (! $max_length) {
4603 $max_length = MAX_IMAGE_LENGTH;
4605 if ($max_length > 0) {
4606 $Image->scaleDown($max_length);
4607 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4609 $width = $Image->getWidth();
4610 $height = $Image->getHeight();
4612 // create a new resource-id if not already provided
4613 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4615 if ($mediatype == "photo") {
4616 // upload normal image (scales 0, 1, 2)
4617 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4619 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4621 logger("photo upload: image upload with scale 0 (original size) failed");
4623 if ($width > 640 || $height > 640) {
4624 $Image->scaleDown(640);
4625 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4627 logger("photo upload: image upload with scale 1 (640x640) failed");
4631 if ($width > 320 || $height > 320) {
4632 $Image->scaleDown(320);
4633 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4635 logger("photo upload: image upload with scale 2 (320x320) failed");
4638 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4639 } elseif ($mediatype == "profileimage") {
4640 // upload profile image (scales 4, 5, 6)
4641 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4643 if ($width > 175 || $height > 175) {
4644 $Image->scaleDown(175);
4645 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4647 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4651 if ($width > 80 || $height > 80) {
4652 $Image->scaleDown(80);
4653 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4655 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4659 if ($width > 48 || $height > 48) {
4660 $Image->scaleDown(48);
4661 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4663 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4666 $Image->__destruct();
4667 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4671 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4672 if ($photo_id == null && $mediatype == "photo") {
4673 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4675 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4676 return prepare_photo_data($type, false, $hash);
4678 throw new InternalServerErrorException("image upload failed");
4684 * @param string $hash
4685 * @param string $allow_cid
4686 * @param string $deny_cid
4687 * @param string $allow_gid
4688 * @param string $deny_gid
4689 * @param string $filetype
4690 * @param boolean $visibility
4692 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4694 // get data about the api authenticated user
4695 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4696 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4699 $arr['guid'] = get_guid(32);
4700 $arr['uid'] = intval(api_user());
4702 $arr['parent-uri'] = $uri;
4703 $arr['type'] = 'photo';
4705 $arr['resource-id'] = $hash;
4706 $arr['contact-id'] = $owner_record[0]['id'];
4707 $arr['owner-name'] = $owner_record[0]['name'];
4708 $arr['owner-link'] = $owner_record[0]['url'];
4709 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4710 $arr['author-name'] = $owner_record[0]['name'];
4711 $arr['author-link'] = $owner_record[0]['url'];
4712 $arr['author-avatar'] = $owner_record[0]['thumb'];
4714 $arr['allow_cid'] = $allow_cid;
4715 $arr['allow_gid'] = $allow_gid;
4716 $arr['deny_cid'] = $deny_cid;
4717 $arr['deny_gid'] = $deny_gid;
4718 $arr['visible'] = $visibility;
4722 'image/jpeg' => 'jpg',
4723 'image/png' => 'png',
4724 'image/gif' => 'gif'
4727 // adds link to the thumbnail scale photo
4728 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4729 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4732 // do the magic for storing the item in the database and trigger the federation to other contacts
4738 * @param string $type
4740 * @param string $photo_id
4744 function prepare_photo_data($type, $scale, $photo_id)
4746 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4747 $data_sql = ($scale === false ? "" : "data, ");
4749 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4750 // clients needs to convert this in their way for further processing
4752 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4753 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4754 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4755 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4757 intval(local_user()),
4763 'image/jpeg' => 'jpg',
4764 'image/png' => 'png',
4765 'image/gif' => 'gif'
4768 // prepare output data for photo
4769 if (DBM::is_result($r)) {
4770 $data = ['photo' => $r[0]];
4771 $data['photo']['id'] = $data['photo']['resource-id'];
4772 if ($scale !== false) {
4773 $data['photo']['data'] = base64_encode($data['photo']['data']);
4775 unset($data['photo']['datasize']); //needed only with scale param
4777 if ($type == "xml") {
4778 $data['photo']['links'] = [];
4779 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4780 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4782 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4785 $data['photo']['link'] = [];
4786 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4788 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4789 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4793 unset($data['photo']['resource-id']);
4794 unset($data['photo']['minscale']);
4795 unset($data['photo']['maxscale']);
4797 throw new NotFoundException();
4800 // retrieve item element for getting activities (like, dislike etc.) related to photo
4802 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4803 intval(local_user()),
4806 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4808 // retrieve comments on photo
4810 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4811 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4812 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4813 `contact`.`id` AS `cid`
4815 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4816 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4817 WHERE `item`.`parent` = %d AND `item`.`visible`
4818 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4819 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4820 intval($item[0]['parent']),
4822 dbesc(ACTIVITY_POST)
4825 // prepare output of comments
4826 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4828 if ($type == "xml") {
4830 foreach ($commentData as $comment) {
4831 $comments[$k++ . ":comment"] = $comment;
4834 foreach ($commentData as $comment) {
4835 $comments[] = $comment;
4838 $data['photo']['friendica_comments'] = $comments;
4840 // include info if rights on photo and rights on item are mismatching
4841 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4842 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4843 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4844 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4845 $data['photo']['rights_mismatch'] = $rights_mismatch;
4852 * Similar as /mod/redir.php
4853 * redirect to 'url' after dfrn auth
4855 * Why this when there is mod/redir.php already?
4856 * This use api_user() and api_login()
4859 * c_url: url of remote contact to auth to
4860 * url: string, url to redirect after auth
4862 function api_friendica_remoteauth()
4864 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4865 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4867 if ($url === '' || $c_url === '') {
4868 throw new BadRequestException("Wrong parameters.");
4871 $c_url = normalise_link($c_url);
4875 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4877 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4878 throw new BadRequestException("Unknown contact");
4881 $cid = $contact['id'];
4883 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4885 if ($contact['duplex'] && $contact['issued-id']) {
4886 $orig_id = $contact['issued-id'];
4887 $dfrn_id = '1:' . $orig_id;
4889 if ($contact['duplex'] && $contact['dfrn-id']) {
4890 $orig_id = $contact['dfrn-id'];
4891 $dfrn_id = '0:' . $orig_id;
4894 $sec = random_string();
4897 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4898 VALUES( %d, %s, '%s', '%s', %d )",
4906 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4907 $dest = ($url ? '&destination_url=' . $url : '');
4909 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4910 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4911 . '&type=profile&sec=' . $sec . $dest . $quiet
4914 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4917 * @brief Return the item shared, if the item contains only the [share] tag
4919 * @param array $item Sharer item
4920 * @return array|false Shared item or false if not a reshare
4922 function api_share_as_retweet(&$item)
4924 $body = trim($item["body"]);
4926 if (Diaspora::isReshare($body, false)===false) {
4930 /// @TODO "$1" should maybe mean '$1' ?
4931 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4933 * Skip if there is no shared message in there
4934 * we already checked this in diaspora::isReshare()
4935 * but better one more than one less...
4937 if ($body == $attributes) {
4942 // build the fake reshared item
4943 $reshared_item = $item;
4946 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4947 if ($matches[1] != "") {
4948 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4951 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4952 if ($matches[1] != "") {
4953 $author = $matches[1];
4957 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4958 if ($matches[1] != "") {
4959 $profile = $matches[1];
4962 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4963 if ($matches[1] != "") {
4964 $profile = $matches[1];
4968 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4969 if ($matches[1] != "") {
4970 $avatar = $matches[1];
4973 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4974 if ($matches[1] != "") {
4975 $avatar = $matches[1];
4979 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4980 if ($matches[1] != "") {
4981 $link = $matches[1];
4984 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4985 if ($matches[1] != "") {
4986 $link = $matches[1];
4990 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4991 if ($matches[1] != "") {
4992 $posted = $matches[1];
4995 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4996 if ($matches[1] != "") {
4997 $posted = $matches[1];
5000 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5002 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5006 $reshared_item["body"] = $shared_body;
5007 $reshared_item["author-name"] = $author;
5008 $reshared_item["author-link"] = $profile;
5009 $reshared_item["author-avatar"] = $avatar;
5010 $reshared_item["plink"] = $link;
5011 $reshared_item["created"] = $posted;
5012 $reshared_item["edited"] = $posted;
5014 return $reshared_item;
5019 * @param string $profile
5021 * @return string|false
5022 * @todo remove trailing junk from profile url
5023 * @todo pump.io check has to check the website
5025 function api_get_nick($profile)
5030 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5031 dbesc(normalise_link($profile))
5034 if (DBM::is_result($r)) {
5035 $nick = $r[0]["nick"];
5040 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5041 dbesc(normalise_link($profile))
5044 if (DBM::is_result($r)) {
5045 $nick = $r[0]["nick"];
5050 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5051 if ($friendica != $profile) {
5057 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5058 if ($diaspora != $profile) {
5064 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5065 if ($twitter != $profile) {
5072 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5073 if ($StatusnetHost != $profile) {
5074 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5075 if ($StatusnetUser != $profile) {
5076 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5077 $user = json_decode($UserData);
5079 $nick = $user->screen_name;
5085 // To-Do: look at the page if its really a pumpio site
5086 //if (!$nick == "") {
5087 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5088 // if ($pumpio != $profile)
5090 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5103 * @param array $item
5107 function api_in_reply_to($item)
5111 $in_reply_to['status_id'] = null;
5112 $in_reply_to['user_id'] = null;
5113 $in_reply_to['status_id_str'] = null;
5114 $in_reply_to['user_id_str'] = null;
5115 $in_reply_to['screen_name'] = null;
5117 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5119 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5120 intval($item['uid']),
5121 dbesc($item['thr-parent'])
5124 if (DBM::is_result($r)) {
5125 $in_reply_to['status_id'] = intval($r[0]['id']);
5127 $in_reply_to['status_id'] = intval($item['parent']);
5130 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5133 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
5134 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5135 WHERE `item`.`id` = %d LIMIT 1",
5136 intval($in_reply_to['status_id'])
5139 if (DBM::is_result($r)) {
5140 if ($r[0]['nick'] == "") {
5141 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5144 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5145 $in_reply_to['user_id'] = intval($r[0]['id']);
5146 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5149 // There seems to be situation, where both fields are identical:
5150 // https://github.com/friendica/friendica/issues/1010
5151 // This is a bugfix for that.
5152 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5153 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5154 $in_reply_to['status_id'] = null;
5155 $in_reply_to['user_id'] = null;
5156 $in_reply_to['status_id_str'] = null;
5157 $in_reply_to['user_id_str'] = null;
5158 $in_reply_to['screen_name'] = null;
5162 return $in_reply_to;
5167 * @param string $Text
5171 function api_clean_plain_items($Text)
5173 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5175 $Text = bb_CleanPictureLinks($Text);
5176 $URLSearchString = "^\[\]";
5178 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
5180 if ($include_entities == "true") {
5181 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
5184 // Simplify "attachment" element
5185 $Text = api_clean_attachments($Text);
5191 * @brief Removes most sharing information for API text export
5193 * @param string $body The original body
5195 * @return string Cleaned body
5197 function api_clean_attachments($body)
5199 $data = BBCode::getAttachmentData($body);
5206 if (isset($data["text"])) {
5207 $body = $data["text"];
5209 if (($body == "") && isset($data["title"])) {
5210 $body = $data["title"];
5212 if (isset($data["url"])) {
5213 $body .= "\n".$data["url"];
5215 $body .= $data["after"];
5222 * @param array $contacts
5226 function api_best_nickname(&$contacts)
5230 if (count($contact) == 0) {
5234 foreach ($contacts as $contact) {
5235 if ($contact["network"] == "") {
5236 $contact["network"] = "dfrn";
5237 $best_contact = [$contact];
5241 if (sizeof($best_contact) == 0) {
5242 foreach ($contacts as $contact) {
5243 if ($contact["network"] == "dfrn") {
5244 $best_contact = [$contact];
5249 if (sizeof($best_contact) == 0) {
5250 foreach ($contacts as $contact) {
5251 if ($contact["network"] == "dspr") {
5252 $best_contact = [$contact];
5257 if (sizeof($best_contact) == 0) {
5258 foreach ($contacts as $contact) {
5259 if ($contact["network"] == "stat") {
5260 $best_contact = [$contact];
5265 if (sizeof($best_contact) == 0) {
5266 foreach ($contacts as $contact) {
5267 if ($contact["network"] == "pump") {
5268 $best_contact = [$contact];
5273 if (sizeof($best_contact) == 0) {
5274 foreach ($contacts as $contact) {
5275 if ($contact["network"] == "twit") {
5276 $best_contact = [$contact];
5281 if (sizeof($best_contact) == 1) {
5282 $contacts = $best_contact;
5284 $contacts = [$contacts[0]];
5289 * Return all or a specified group of the user with the containing contacts.
5291 * @param string $type Return type (atom, rss, xml, json)
5293 * @return array|string
5295 function api_friendica_group_show($type)
5299 if (api_user() === false) {
5300 throw new ForbiddenException();
5304 $user_info = api_get_user($a);
5305 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5306 $uid = $user_info['uid'];
5308 // get data of the specified group id or all groups if not specified
5311 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5315 // error message if specified gid is not in database
5316 if (!DBM::is_result($r)) {
5317 throw new BadRequestException("gid not available");
5321 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5326 // loop through all groups and retrieve all members for adding data in the user array
5327 foreach ($r as $rr) {
5328 $members = Contact::getByGroupId($rr['id']);
5331 if ($type == "xml") {
5332 $user_element = "users";
5334 foreach ($members as $member) {
5335 $user = api_get_user($a, $member['nurl']);
5336 $users[$k++.":user"] = $user;
5339 $user_element = "user";
5340 foreach ($members as $member) {
5341 $user = api_get_user($a, $member['nurl']);
5345 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5347 return api_format_data("groups", $type, ['group' => $grps]);
5349 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5353 * Delete the specified group of the user.
5355 * @param string $type Return type (atom, rss, xml, json)
5357 * @return array|string
5359 function api_friendica_group_delete($type)
5363 if (api_user() === false) {
5364 throw new ForbiddenException();
5368 $user_info = api_get_user($a);
5369 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5370 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5371 $uid = $user_info['uid'];
5373 // error if no gid specified
5374 if ($gid == 0 || $name == "") {
5375 throw new BadRequestException('gid or name not specified');
5378 // get data of the specified group id
5380 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5384 // error message if specified gid is not in database
5385 if (!DBM::is_result($r)) {
5386 throw new BadRequestException('gid not available');
5389 // get data of the specified group id and group name
5391 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5396 // error message if specified gid is not in database
5397 if (!DBM::is_result($rname)) {
5398 throw new BadRequestException('wrong group name');
5402 $ret = Group::removeByName($uid, $name);
5405 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5406 return api_format_data("group_delete", $type, ['result' => $success]);
5408 throw new BadRequestException('other API error');
5411 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5415 * Create the specified group with the posted array of contacts.
5417 * @param string $type Return type (atom, rss, xml, json)
5419 * @return array|string
5421 function api_friendica_group_create($type)
5425 if (api_user() === false) {
5426 throw new ForbiddenException();
5430 $user_info = api_get_user($a);
5431 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5432 $uid = $user_info['uid'];
5433 $json = json_decode($_POST['json'], true);
5434 $users = $json['user'];
5436 // error if no name specified
5438 throw new BadRequestException('group name not specified');
5441 // get data of the specified group name
5443 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5447 // error message if specified group name already exists
5448 if (DBM::is_result($rname)) {
5449 throw new BadRequestException('group name already exists');
5452 // check if specified group name is a deleted group
5454 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5458 // error message if specified group name already exists
5459 if (DBM::is_result($rname)) {
5460 $reactivate_group = true;
5464 $ret = Group::create($uid, $name);
5466 $gid = Group::getIdByName($uid, $name);
5468 throw new BadRequestException('other API error');
5472 $erroraddinguser = false;
5474 foreach ($users as $user) {
5475 $cid = $user['cid'];
5476 // check if user really exists as contact
5478 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5482 if (count($contact)) {
5483 Group::addMember($gid, $cid);
5485 $erroraddinguser = true;
5486 $errorusers[] = $cid;
5490 // return success message incl. missing users in array
5491 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5492 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5493 return api_format_data("group_create", $type, ['result' => $success]);
5495 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5499 * Update the specified group with the posted array of contacts.
5501 * @param string $type Return type (atom, rss, xml, json)
5503 * @return array|string
5505 function api_friendica_group_update($type)
5509 if (api_user() === false) {
5510 throw new ForbiddenException();
5514 $user_info = api_get_user($a);
5515 $uid = $user_info['uid'];
5516 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5517 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5518 $json = json_decode($_POST['json'], true);
5519 $users = $json['user'];
5521 // error if no name specified
5523 throw new BadRequestException('group name not specified');
5526 // error if no gid specified
5528 throw new BadRequestException('gid not specified');
5532 $members = Contact::getByGroupId($gid);
5533 foreach ($members as $member) {
5534 $cid = $member['id'];
5535 foreach ($users as $user) {
5536 $found = ($user['cid'] == $cid ? true : false);
5539 Group::removeMemberByName($uid, $name, $cid);
5544 $erroraddinguser = false;
5546 foreach ($users as $user) {
5547 $cid = $user['cid'];
5548 // check if user really exists as contact
5550 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5555 if (count($contact)) {
5556 Group::addMember($gid, $cid);
5558 $erroraddinguser = true;
5559 $errorusers[] = $cid;
5563 // return success message incl. missing users in array
5564 $status = ($erroraddinguser ? "missing user" : "ok");
5565 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5566 return api_format_data("group_update", $type, ['result' => $success]);
5569 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5573 * @param string $type Return type (atom, rss, xml, json)
5575 * @return array|string
5577 function api_friendica_activity($type)
5581 if (api_user() === false) {
5582 throw new ForbiddenException();
5584 $verb = strtolower($a->argv[3]);
5585 $verb = preg_replace("|\..*$|", "", $verb);
5587 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5589 $res = Item::performLike($id, $verb);
5592 if ($type == "xml") {
5597 return api_format_data('ok', $type, ['ok' => $ok]);
5599 throw new BadRequestException('Error adding activity');
5603 /// @TODO move to top of file or somewhere better
5604 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5605 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5606 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5607 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5608 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5609 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5610 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5611 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5612 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5613 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5616 * @brief Returns notifications
5618 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5621 function api_friendica_notification($type)
5625 if (api_user() === false) {
5626 throw new ForbiddenException();
5629 throw new BadRequestException("Invalid argument count");
5631 $nm = new NotificationsManager();
5633 $notes = $nm->getAll([], "+seen -date", 50);
5635 if ($type == "xml") {
5637 foreach ($notes as $note) {
5638 $xmlnotes[] = ["@attributes" => $note];
5644 return api_format_data("notes", $type, ['note' => $notes]);
5648 * POST request with 'id' param as notification id
5650 * @brief Set notification as seen and returns associated item (if possible)
5652 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5655 function api_friendica_notification_seen($type)
5659 if (api_user() === false) {
5660 throw new ForbiddenException();
5663 throw new BadRequestException("Invalid argument count");
5666 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5668 $nm = new NotificationsManager();
5669 $note = $nm->getByID($id);
5670 if (is_null($note)) {
5671 throw new BadRequestException("Invalid argument");
5674 $nm->setSeen($note);
5675 if ($note['otype']=='item') {
5676 // would be really better with an ItemsManager and $im->getByID() :-P
5678 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5679 intval($note['iid']),
5680 intval(local_user())
5683 // we found the item, return it to the user
5684 $user_info = api_get_user($a);
5685 $ret = api_format_items($r, $user_info, false, $type);
5686 $data = ['status' => $ret];
5687 return api_format_data("status", $type, $data);
5689 // the item can't be found, but we set the note as seen, so we count this as a success
5691 return api_format_data('result', $type, ['result' => "success"]);
5694 /// @TODO move to top of file or somewhere better
5695 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5696 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5699 * @brief update a direct_message to seen state
5701 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5702 * @return string (success result=ok, error result=error with error message)
5704 function api_friendica_direct_messages_setseen($type)
5707 if (api_user() === false) {
5708 throw new ForbiddenException();
5712 $user_info = api_get_user($a);
5713 $uid = $user_info['uid'];
5714 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5716 // return error if id is zero
5718 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5719 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5722 // get data of the specified message id
5724 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5729 // error message if specified id is not in database
5730 if (!DBM::is_result($r)) {
5731 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5732 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5735 // update seen indicator
5737 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5744 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5745 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5747 $answer = ['result' => 'error', 'message' => 'unknown error'];
5748 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5752 /// @TODO move to top of file or somewhere better
5753 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5756 * @brief search for direct_messages containing a searchstring through api
5758 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5759 * @return string (success: success=true if found and search_result contains found messages,
5760 * success=false if nothing was found, search_result='nothing found',
5761 * error: result=error with error message)
5763 function api_friendica_direct_messages_search($type)
5767 if (api_user() === false) {
5768 throw new ForbiddenException();
5772 $user_info = api_get_user($a);
5773 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5774 $uid = $user_info['uid'];
5776 // error if no searchstring specified
5777 if ($searchstring == "") {
5778 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5779 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5782 // get data for the specified searchstring
5784 "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",
5786 dbesc('%'.$searchstring.'%')
5789 $profile_url = $user_info["url"];
5791 // message if nothing was found
5792 if (!DBM::is_result($r)) {
5793 $success = ['success' => false, 'search_results' => 'problem with query'];
5794 } elseif (count($r) == 0) {
5795 $success = ['success' => false, 'search_results' => 'nothing found'];
5798 foreach ($r as $item) {
5799 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5800 $recipient = $user_info;
5801 $sender = api_get_user($a, normalise_link($item['contact-url']));
5802 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5803 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5804 $sender = $user_info;
5807 $ret[] = api_format_messages($item, $recipient, $sender);
5809 $success = ['success' => true, 'search_results' => $ret];
5812 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5815 /// @TODO move to top of file or somewhere better
5816 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5819 * @brief return data of all the profiles a user has to the client
5821 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5824 function api_friendica_profile_show($type)
5828 if (api_user() === false) {
5829 throw new ForbiddenException();
5833 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5835 // retrieve general information about profiles for user
5836 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5837 $directory = Config::get('system', 'directory');
5839 // get data of the specified profile id or all profiles of the user if not specified
5840 if ($profileid != 0) {
5842 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5847 // error message if specified gid is not in database
5848 if (!DBM::is_result($r)) {
5849 throw new BadRequestException("profile_id not available");
5853 "SELECT * FROM `profile` WHERE `uid` = %d",
5857 // loop through all returned profiles and retrieve data and users
5859 foreach ($r as $rr) {
5860 $profile = api_format_items_profiles($rr);
5862 // select all users from contact table, loop and prepare standard return for user data
5865 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5867 intval($rr['profile_id'])
5870 foreach ($r as $rr) {
5871 $user = api_get_user($a, $rr['nurl']);
5872 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5874 $profile['users'] = $users;
5876 // add prepared profile data to array for final return
5877 if ($type == "xml") {
5878 $profiles[$k++ . ":profile"] = $profile;
5880 $profiles[] = $profile;
5884 // return settings, authenticated user and profiles data
5885 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5887 $result = ['multi_profiles' => $multi_profiles ? true : false,
5888 'global_dir' => $directory,
5889 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5890 'profiles' => $profiles];
5891 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5893 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5896 * Returns a list of saved searches.
5898 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5900 * @param string $type Return format: json or xml
5902 * @return string|array
5904 function api_saved_searches_list($type)
5906 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5909 while ($term = $terms->fetch()) {
5911 'name' => $term['term'],
5912 'query' => $term['term'],
5913 'id_str' => $term['id'],
5914 'id' => intval($term['id'])
5920 return api_format_data("terms", $type, ['terms' => $result]);
5923 /// @TODO move to top of file or somewhere better
5924 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5927 @TODO Maybe open to implement?
5929 [pagename] => api/1.1/statuses/lookup.json
5930 [id] => 605138389168451584
5931 [include_cards] => true
5932 [cards_platform] => Android-12
5933 [include_entities] => true
5934 [include_my_retweet] => 1
5936 [include_reply_count] => true
5937 [include_descendent_reply_count] => true
5941 Not implemented by now:
5942 statuses/retweets_of_me
5947 account/update_location
5948 account/update_profile_background_image
5951 friendica/profile/update
5952 friendica/profile/create
5953 friendica/profile/delete
5955 Not implemented in status.net:
5956 statuses/retweeted_to_me
5957 statuses/retweeted_by_me
5958 direct_messages/destroy
5960 account/update_delivery_device
5961 notifications/follow