3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\Addon;
15 use Friendica\Core\Config;
16 use Friendica\Core\L10n;
17 use Friendica\Core\NotificationsManager;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
21 use Friendica\Database\DBM;
22 use Friendica\Model\Contact;
23 use Friendica\Model\Group;
24 use Friendica\Model\Item;
25 use Friendica\Model\Mail;
26 use Friendica\Model\Photo;
27 use Friendica\Model\User;
28 use Friendica\Network\FKOAuth1;
29 use Friendica\Network\HTTPException;
30 use Friendica\Network\HTTPException\BadRequestException;
31 use Friendica\Network\HTTPException\ForbiddenException;
32 use Friendica\Network\HTTPException\InternalServerErrorException;
33 use Friendica\Network\HTTPException\MethodNotAllowedException;
34 use Friendica\Network\HTTPException\NotFoundException;
35 use Friendica\Network\HTTPException\NotImplementedException;
36 use Friendica\Network\HTTPException\TooManyRequestsException;
37 use Friendica\Network\HTTPException\UnauthorizedException;
38 use Friendica\Object\Image;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Network;
42 use Friendica\Util\XML;
44 require_once 'include/conversation.php';
45 require_once 'mod/share.php';
46 require_once 'mod/item.php';
47 require_once 'include/security.php';
48 require_once 'mod/wall_upload.php';
49 require_once 'mod/proxy.php';
51 define('API_METHOD_ANY', '*');
52 define('API_METHOD_GET', 'GET');
53 define('API_METHOD_POST', 'POST,PUT');
54 define('API_METHOD_DELETE', 'POST,DELETE');
60 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
61 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
62 * into a page, and visitors will post something without noticing it).
64 * @brief Auth API user
68 if (x($_SESSION, 'allow_api')) {
76 * Clients can send 'source' parameter to be show in post metadata
77 * as "sent via <source>".
78 * Some clients doesn't send a source param, we support ones we know
81 * @brief Get source name from API client
84 * Client source name, default to "api" if unset/unknown
88 if (requestdata('source')) {
89 return requestdata('source');
92 // Support for known clients that doesn't send a source name
93 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
97 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
103 * @brief Format date for API
105 * @param string $str Source date, as UTC
106 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
108 function api_date($str)
110 // Wed May 23 06:01:13 +0000 2007
111 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
115 * Register a function to be the endpoint for defined API path.
117 * @brief Register API endpoint
119 * @param string $path API URL path, relative to System::baseUrl()
120 * @param string $func Function name to call on path request
121 * @param bool $auth API need logged user
122 * @param string $method HTTP method reqiured to call this endpoint.
123 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
124 * Default to API_METHOD_ANY
126 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
136 // Workaround for hotot
137 $path = str_replace("api/", "api/1.1/", $path);
147 * Log in user via OAuth1 or Simple HTTP Auth.
148 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
150 * @brief Login API user
152 * @param object $a App
153 * @hook 'authenticate'
155 * 'username' => username from login form
156 * 'password' => password from login form
157 * 'authenticated' => return status,
158 * 'user_record' => return authenticated user record
160 * array $user logged user record
162 function api_login(App $a)
164 $oauth1 = new FKOAuth1();
167 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
168 if (!is_null($token)) {
169 $oauth1->loginUser($token->uid);
170 Addon::callHooks('logged_in', $a->user);
173 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
174 var_dump($consumer, $token);
176 } catch (Exception $e) {
180 // workaround for HTTP-auth in CGI mode
181 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
182 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
183 if (strlen($userpass)) {
184 list($name, $password) = explode(':', $userpass);
185 $_SERVER['PHP_AUTH_USER'] = $name;
186 $_SERVER['PHP_AUTH_PW'] = $password;
190 if (!x($_SERVER, 'PHP_AUTH_USER')) {
191 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
192 header('WWW-Authenticate: Basic realm="Friendica"');
193 throw new UnauthorizedException("This API requires login");
196 $user = $_SERVER['PHP_AUTH_USER'];
197 $password = $_SERVER['PHP_AUTH_PW'];
199 // allow "user@server" login (but ignore 'server' part)
200 $at = strstr($user, "@", true);
205 // next code from mod/auth.php. needs better solution
209 'username' => trim($user),
210 'password' => trim($password),
211 'authenticated' => 0,
212 'user_record' => null,
216 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
217 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
218 * and later addons should not interfere with an earlier one that succeeded.
220 Addon::callHooks('authenticate', $addon_auth);
222 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
223 $record = $addon_auth['user_record'];
225 $user_id = User::authenticate(trim($user), trim($password));
227 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
231 if (!DBM::is_result($record)) {
232 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
233 header('WWW-Authenticate: Basic realm="Friendica"');
234 //header('HTTP/1.0 401 Unauthorized');
235 //die('This api requires login');
236 throw new UnauthorizedException("This API requires login");
239 authenticate_success($record);
241 $_SESSION["allow_api"] = true;
243 Addon::callHooks('logged_in', $a->user);
247 * API endpoints can define which HTTP method to accept when called.
248 * This function check the current HTTP method agains endpoint
251 * @brief Check HTTP method of called API
253 * @param string $method Required methods, uppercase, separated by comma
256 function api_check_method($method)
258 if ($method == "*") {
261 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
265 * Authenticate user, call registered API function, set HTTP headers
267 * @brief Main API entry point
269 * @param object $a App
270 * @return string API call result
272 function api_call(App $a)
274 global $API, $called_api;
277 if (strpos($a->query_string, ".xml") > 0) {
280 if (strpos($a->query_string, ".json") > 0) {
283 if (strpos($a->query_string, ".rss") > 0) {
286 if (strpos($a->query_string, ".atom") > 0) {
291 foreach ($API as $p => $info) {
292 if (strpos($a->query_string, $p) === 0) {
293 if (!api_check_method($info['method'])) {
294 throw new MethodNotAllowedException();
297 $called_api = explode("/", $p);
298 //unset($_SERVER['PHP_AUTH_USER']);
300 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
301 if ($info['auth'] === true && api_user() === false) {
305 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
306 logger('API parameters: ' . print_r($_REQUEST, true));
308 $stamp = microtime(true);
309 $return = call_user_func($info['func'], $type);
310 $duration = (float) (microtime(true) - $stamp);
311 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
313 if (Config::get("system", "profiler")) {
314 $duration = microtime(true)-$a->performance["start"];
316 /// @TODO round() really everywhere?
318 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
319 "Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
320 round($a->performance["database"] - $a->performance["database_write"], 3),
321 round($a->performance["database_write"], 3),
322 round($a->performance["cache"], 3),
323 round($a->performance["cache_write"], 3),
324 round($a->performance["network"], 2),
325 round($a->performance["file"], 2),
326 round($duration - ($a->performance["database"]
327 + $a->performance["cache"] + $a->performance["cache_write"]
328 + $a->performance["network"] + $a->performance["file"]), 2),
334 if (Config::get("rendertime", "callstack")) {
335 $o = "Database Read:\n";
336 foreach ($a->callstack["database"] as $func => $time) {
337 $time = round($time, 3);
339 $o .= $func . ": " . $time . "\n";
342 $o .= "\nDatabase Write:\n";
343 foreach ($a->callstack["database_write"] as $func => $time) {
344 $time = round($time, 3);
346 $o .= $func . ": " . $time . "\n";
350 $o = "Cache Read:\n";
351 foreach ($a->callstack["cache"] as $func => $time) {
352 $time = round($time, 3);
354 $o .= $func . ": " . $time . "\n";
357 $o .= "\nCache Write:\n";
358 foreach ($a->callstack["cache_write"] as $func => $time) {
359 $time = round($time, 3);
361 $o .= $func . ": " . $time . "\n";
365 $o .= "\nNetwork:\n";
366 foreach ($a->callstack["network"] as $func => $time) {
367 $time = round($time, 3);
369 $o .= $func . ": " . $time . "\n";
372 logger($o, LOGGER_DEBUG);
376 if (false === $return) {
378 * api function returned false withour throw an
379 * exception. This should not happend, throw a 500
381 throw new InternalServerErrorException();
386 header("Content-Type: text/xml");
389 header("Content-Type: application/json");
390 foreach ($return as $rr) {
391 $json = json_encode($rr);
393 if (x($_GET, 'callback')) {
394 $json = $_GET['callback'] . "(" . $json . ")";
399 header("Content-Type: application/rss+xml");
400 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
403 header("Content-Type: application/atom+xml");
404 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
411 logger('API call not implemented: ' . $a->query_string);
412 throw new NotImplementedException();
413 } catch (HTTPException $e) {
414 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
415 return api_error($type, $e);
420 * @brief Format API error string
422 * @param string $type Return type (xml, json, rss, as)
423 * @param object $e HTTPException Error object
424 * @return string error message formatted as $type
426 function api_error($type, $e)
430 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
431 /// @TODO: https://dev.twitter.com/overview/api/response-codes
433 $error = ["error" => $error,
434 "code" => $e->httpcode . " " . $e->httpdesc,
435 "request" => $a->query_string];
437 $return = api_format_data('status', $type, ['status' => $error]);
441 header("Content-Type: text/xml");
444 header("Content-Type: application/json");
445 $return = json_encode($return);
448 header("Content-Type: application/rss+xml");
451 header("Content-Type: application/atom+xml");
459 * @brief Set values for RSS template
462 * @param array $arr Array to be passed to template
463 * @param array $user_info User info
465 * @todo find proper type-hints
467 function api_rss_extra(App $a, $arr, $user_info)
469 if (is_null($user_info)) {
470 $user_info = api_get_user($a);
473 $arr['$user'] = $user_info;
475 'alternate' => $user_info['url'],
476 'self' => System::baseUrl() . "/" . $a->query_string,
477 'base' => System::baseUrl(),
478 'updated' => api_date(null),
479 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
480 'language' => $user_info['language'],
481 'logo' => System::baseUrl() . "/images/friendica-32.png",
489 * @brief Unique contact to contact url.
491 * @param int $id Contact id
492 * @return bool|string
493 * Contact url or False if contact id is unknown
495 function api_unique_id_to_nurl($id)
497 $r = dba::selectFirst('contact', ['nurl'], ['uid' => 0, 'id' => $id]);
499 if (DBM::is_result($r)) {
507 * @brief Get user info array.
509 * @param object $a App
510 * @param int|string $contact_id Contact ID or URL
512 function api_get_user(App $a, $contact_id = null)
520 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
522 // Searching for contact URL
523 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
524 $user = dbesc(normalise_link($contact_id));
526 $extra_query = "AND `contact`.`nurl` = '%s' ";
527 if (api_user() !== false) {
528 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
532 // Searching for contact id with uid = 0
533 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
534 $user = dbesc(api_unique_id_to_nurl($contact_id));
537 throw new BadRequestException("User not found.");
541 $extra_query = "AND `contact`.`nurl` = '%s' ";
542 if (api_user() !== false) {
543 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
547 if (is_null($user) && x($_GET, 'user_id')) {
548 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
551 throw new BadRequestException("User not found.");
555 $extra_query = "AND `contact`.`nurl` = '%s' ";
556 if (api_user() !== false) {
557 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
560 if (is_null($user) && x($_GET, 'screen_name')) {
561 $user = dbesc($_GET['screen_name']);
562 $extra_query = "AND `contact`.`nick` = '%s' ";
563 if (api_user() !== false) {
564 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
568 if (is_null($user) && x($_GET, 'profileurl')) {
569 $user = dbesc(normalise_link($_GET['profileurl']));
570 $extra_query = "AND `contact`.`nurl` = '%s' ";
571 if (api_user() !== false) {
572 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
576 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
577 $argid = count($called_api);
578 list($user, $null) = explode(".", $a->argv[$argid]);
579 if (is_numeric($user)) {
580 $user = dbesc(api_unique_id_to_nurl($user));
587 $extra_query = "AND `contact`.`nurl` = '%s' ";
588 if (api_user() !== false) {
589 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
592 $user = dbesc($user);
593 $extra_query = "AND `contact`.`nick` = '%s' ";
594 if (api_user() !== false) {
595 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
600 logger("api_get_user: user ".$user, LOGGER_DEBUG);
603 if (api_user() === false) {
607 $user = $_SESSION['uid'];
608 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
612 logger('api_user: ' . $extra_query . ', user: ' . $user);
616 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
622 // Selecting the id by priority, friendica first
623 api_best_nickname($uinfo);
625 // if the contact wasn't found, fetch it from the contacts with uid = 0
626 if (!DBM::is_result($uinfo)) {
630 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
633 if (DBM::is_result($r)) {
634 $network_name = ContactSelector::networkToName($r[0]['network'], $r[0]['url']);
636 // If no nick where given, extract it from the address
637 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
638 $r[0]['nick'] = api_get_nick($r[0]["url"]);
643 'id_str' => (string) $r[0]["id"],
644 'name' => $r[0]["name"],
645 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
646 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
647 'description' => $r[0]["about"],
648 'profile_image_url' => $r[0]["micro"],
649 'profile_image_url_https' => $r[0]["micro"],
650 'url' => $r[0]["url"],
651 'protected' => false,
652 'followers_count' => 0,
653 'friends_count' => 0,
655 'created_at' => api_date($r[0]["created"]),
656 'favourites_count' => 0,
658 'time_zone' => 'UTC',
659 'geo_enabled' => false,
661 'statuses_count' => 0,
663 'contributors_enabled' => false,
664 'is_translator' => false,
665 'is_translation_enabled' => false,
666 'following' => false,
667 'follow_request_sent' => false,
668 'statusnet_blocking' => false,
669 'notifications' => false,
670 'statusnet_profile_url' => $r[0]["url"],
672 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
674 'network' => $r[0]["network"],
679 throw new BadRequestException("User not found.");
683 if ($uinfo[0]['self']) {
684 if ($uinfo[0]['network'] == "") {
685 $uinfo[0]['network'] = NETWORK_DFRN;
689 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
693 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
697 /// @TODO old-lost code? (twice)
698 // Counting is deactivated by now, due to performance issues
699 // count public wall messages
700 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
701 // intval($uinfo[0]['uid'])
703 //$countitms = $r[0]['count'];
706 // Counting is deactivated by now, due to performance issues
707 //$r = q("SELECT count(*) as `count` FROM `item`
708 // WHERE `contact-id` = %d",
709 // intval($uinfo[0]['id'])
711 //$countitms = $r[0]['count'];
715 /// @TODO old-lost code? (twice)
717 // Counting is deactivated by now, due to performance issues
719 $r = q("SELECT count(*) as `count` FROM `contact`
720 WHERE `uid` = %d AND `rel` IN ( %d, %d )
721 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
722 intval($uinfo[0]['uid']),
723 intval(CONTACT_IS_SHARING),
724 intval(CONTACT_IS_FRIEND)
726 $countfriends = $r[0]['count'];
728 $r = q("SELECT count(*) as `count` FROM `contact`
729 WHERE `uid` = %d AND `rel` IN ( %d, %d )
730 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
731 intval($uinfo[0]['uid']),
732 intval(CONTACT_IS_FOLLOWER),
733 intval(CONTACT_IS_FRIEND)
735 $countfollowers = $r[0]['count'];
737 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
738 intval($uinfo[0]['uid'])
740 $starred = $r[0]['count'];
743 if (! $uinfo[0]['self']) {
753 // Add a nick if it isn't present there
754 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
755 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
758 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
760 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
762 if (!empty($profile[0]['about'])) {
763 $description = $profile[0]['about'];
765 $description = $uinfo[0]["about"];
768 if (!empty($usr[0]['default-location'])) {
769 $location = $usr[0]['default-location'];
770 } elseif (!empty($uinfo[0]["location"])) {
771 $location = $uinfo[0]["location"];
773 $location = $network_name;
777 'id' => intval($pcontact_id),
778 'id_str' => (string) intval($pcontact_id),
779 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
780 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
781 'location' => $location,
782 'description' => $description,
783 'profile_image_url' => $uinfo[0]['micro'],
784 'profile_image_url_https' => $uinfo[0]['micro'],
785 'url' => $uinfo[0]['url'],
786 'protected' => false,
787 'followers_count' => intval($countfollowers),
788 'friends_count' => intval($countfriends),
790 'created_at' => api_date($uinfo[0]['created']),
791 'favourites_count' => intval($starred),
793 'time_zone' => 'UTC',
794 'geo_enabled' => false,
796 'statuses_count' => intval($countitms),
798 'contributors_enabled' => false,
799 'is_translator' => false,
800 'is_translation_enabled' => false,
801 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
802 'follow_request_sent' => false,
803 'statusnet_blocking' => false,
804 'notifications' => false,
806 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
807 'statusnet_profile_url' => $uinfo[0]['url'],
808 'uid' => intval($uinfo[0]['uid']),
809 'cid' => intval($uinfo[0]['cid']),
810 'self' => $uinfo[0]['self'],
811 'network' => $uinfo[0]['network'],
814 // If this is a local user and it uses Frio, we can get its color preferences.
816 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
817 if ($theme_info['theme'] === 'frio') {
818 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
819 if ($schema && ($schema != '---')) {
820 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
821 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
822 require_once $schemefile;
825 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
826 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
827 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
833 $link_color = "#6fdbe8";
836 $bgcolor = "#ededed";
839 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
840 $ret['profile_link_color'] = str_replace('#', '', $link_color);
841 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
849 * @brief return api-formatted array for item's author and owner
851 * @param object $a App
852 * @param array $item item from db
853 * @return array(array:author, array:owner)
855 function api_item_get_user(App $a, $item)
857 $status_user = api_get_user($a, $item["author-link"]);
859 $status_user["protected"] = (($item["allow_cid"] != "") ||
860 ($item["allow_gid"] != "") ||
861 ($item["deny_cid"] != "") ||
862 ($item["deny_gid"] != "") ||
865 if ($item['thr-parent'] == $item['uri']) {
866 $owner_user = api_get_user($a, $item["owner-link"]);
868 $owner_user = $status_user;
871 return ([$status_user, $owner_user]);
875 * @brief walks recursively through an array with the possibility to change value and key
877 * @param array $array The array to walk through
878 * @param string $callback The callback function
880 * @return array the transformed array
882 function api_walk_recursive(array &$array, callable $callback)
886 foreach ($array as $k => $v) {
888 if ($callback($v, $k)) {
889 $new_array[$k] = api_walk_recursive($v, $callback);
892 if ($callback($v, $k)) {
903 * @brief Callback function to transform the array in an array that can be transformed in a XML file
905 * @param mixed $item Array item value
906 * @param string $key Array key
908 * @return boolean Should the array item be deleted?
910 function api_reformat_xml(&$item, &$key)
912 if (is_bool($item)) {
913 $item = ($item ? "true" : "false");
916 if (substr($key, 0, 10) == "statusnet_") {
917 $key = "statusnet:".substr($key, 10);
918 } elseif (substr($key, 0, 10) == "friendica_") {
919 $key = "friendica:".substr($key, 10);
921 /// @TODO old-lost code?
923 // $key = "default:".$key;
929 * @brief Creates the XML from a JSON style array
931 * @param array $data JSON style array
932 * @param string $root_element Name of the root element
934 * @return string The XML data
936 function api_create_xml($data, $root_element)
938 $childname = key($data);
939 $data2 = array_pop($data);
942 $namespaces = ["" => "http://api.twitter.com",
943 "statusnet" => "http://status.net/schema/api/1/",
944 "friendica" => "http://friendi.ca/schema/api/1/",
945 "georss" => "http://www.georss.org/georss"];
947 /// @todo Auto detection of needed namespaces
948 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
952 if (is_array($data2)) {
953 api_walk_recursive($data2, "api_reformat_xml");
960 foreach ($data2 as $item) {
961 $data4[$i++.":".$childname] = $item;
967 $data3 = [$root_element => $data2];
969 $ret = XML::fromArray($data3, $xml, false, $namespaces);
974 * @brief Formats the data according to the data type
976 * @param string $root_element Name of the root element
977 * @param string $type Return type (atom, rss, xml, json)
978 * @param array $data JSON style array
980 * @return (string|object|array) XML data or JSON data
982 function api_format_data($root_element, $type, $data)
988 $ret = api_create_xml($data, $root_element);
1003 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
1004 * returns a 401 status code and an error message if not.
1005 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
1007 * @param string $type Return type (atom, rss, xml, json)
1009 function api_account_verify_credentials($type)
1014 if (api_user() === false) {
1015 throw new ForbiddenException();
1018 unset($_REQUEST["user_id"]);
1019 unset($_GET["user_id"]);
1021 unset($_REQUEST["screen_name"]);
1022 unset($_GET["screen_name"]);
1024 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1026 $user_info = api_get_user($a);
1028 // "verified" isn't used here in the standard
1029 unset($user_info["verified"]);
1031 // - Adding last status
1032 if (!$skip_status) {
1033 $user_info["status"] = api_status_show("raw");
1034 if (!count($user_info["status"])) {
1035 unset($user_info["status"]);
1037 unset($user_info["status"]["user"]);
1041 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1042 unset($user_info["uid"]);
1043 unset($user_info["self"]);
1045 return api_format_data("user", $type, ['user' => $user_info]);
1048 /// @TODO move to top of file or somewhere better
1049 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1052 * Get data from $_POST or $_GET
1056 function requestdata($k)
1058 if (x($_POST, $k)) {
1068 * Waitman Gobble Mod
1070 * @param string $type Return type (atom, rss, xml, json)
1072 * @return array|string
1074 function api_statuses_mediap($type)
1078 if (api_user() === false) {
1079 logger('api_statuses_update: no user');
1080 throw new ForbiddenException();
1082 $user_info = api_get_user($a);
1084 $_REQUEST['type'] = 'wall';
1085 $_REQUEST['profile_uid'] = api_user();
1086 $_REQUEST['api_source'] = true;
1087 $txt = requestdata('status');
1088 /// @TODO old-lost code?
1089 //$txt = urldecode(requestdata('status'));
1091 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1092 $txt = html2bb_video($txt);
1093 $config = HTMLPurifier_Config::createDefault();
1094 $config->set('Cache.DefinitionImpl', null);
1095 $purifier = new HTMLPurifier($config);
1096 $txt = $purifier->purify($txt);
1098 $txt = HTML::toBBCode($txt);
1100 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1102 // tell wall_upload function to return img info instead of echo
1103 $_REQUEST['hush'] = 'yeah';
1104 $bebop = wall_upload_post($a);
1106 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1107 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1110 // this should output the last post (the one we just posted).
1111 return api_status_show($type);
1114 /// @TODO move this to top of file or somewhere better!
1115 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1118 * Updates the user’s current status.
1120 * @param string $type Return type (atom, rss, xml, json)
1122 * @return array|string
1123 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1125 function api_statuses_update($type)
1130 if (api_user() === false) {
1131 logger('api_statuses_update: no user');
1132 throw new ForbiddenException();
1137 // convert $_POST array items to the form we use for web posts.
1138 if (requestdata('htmlstatus')) {
1139 $txt = requestdata('htmlstatus');
1140 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1141 $txt = html2bb_video($txt);
1143 $config = HTMLPurifier_Config::createDefault();
1144 $config->set('Cache.DefinitionImpl', null);
1146 $purifier = new HTMLPurifier($config);
1147 $txt = $purifier->purify($txt);
1149 $_REQUEST['body'] = HTML::toBBCode($txt);
1152 $_REQUEST['body'] = requestdata('status');
1155 $_REQUEST['title'] = requestdata('title');
1157 $parent = requestdata('in_reply_to_status_id');
1159 // Twidere sends "-1" if it is no reply ...
1160 if ($parent == -1) {
1164 if (ctype_digit($parent)) {
1165 $_REQUEST['parent'] = $parent;
1167 $_REQUEST['parent_uri'] = $parent;
1170 if (requestdata('lat') && requestdata('long')) {
1171 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1173 $_REQUEST['profile_uid'] = api_user();
1176 $_REQUEST['type'] = 'net-comment';
1178 // Check for throttling (maximum posts per day, week and month)
1179 $throttle_day = Config::get('system', 'throttle_limit_day');
1180 if ($throttle_day > 0) {
1181 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1184 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1185 AND `created` > '%s' AND `id` = `parent`",
1190 if (DBM::is_result($r)) {
1191 $posts_day = $r[0]["posts_day"];
1196 if ($posts_day > $throttle_day) {
1197 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1198 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1199 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));
1203 $throttle_week = Config::get('system', 'throttle_limit_week');
1204 if ($throttle_week > 0) {
1205 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1208 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1209 AND `created` > '%s' AND `id` = `parent`",
1214 if (DBM::is_result($r)) {
1215 $posts_week = $r[0]["posts_week"];
1220 if ($posts_week > $throttle_week) {
1221 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1222 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1223 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));
1227 $throttle_month = Config::get('system', 'throttle_limit_month');
1228 if ($throttle_month > 0) {
1229 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1232 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1233 AND `created` > '%s' AND `id` = `parent`",
1238 if (DBM::is_result($r)) {
1239 $posts_month = $r[0]["posts_month"];
1244 if ($posts_month > $throttle_month) {
1245 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1246 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1247 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));
1251 $_REQUEST['type'] = 'wall';
1254 if (x($_FILES, 'media')) {
1255 // upload the image if we have one
1256 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1257 $media = wall_upload_post($a);
1258 if (strlen($media) > 0) {
1259 $_REQUEST['body'] .= "\n\n" . $media;
1263 // To-Do: Multiple IDs
1264 if (requestdata('media_ids')) {
1266 "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",
1267 intval(requestdata('media_ids')),
1270 if (DBM::is_result($r)) {
1271 $phototypes = Image::supportedTypes();
1272 $ext = $phototypes[$r[0]['type']];
1273 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1274 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1278 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1280 $_REQUEST['api_source'] = true;
1282 if (!x($_REQUEST, "source")) {
1283 $_REQUEST["source"] = api_source();
1286 // call out normal post function
1289 // this should output the last post (the one we just posted).
1290 return api_status_show($type);
1293 /// @TODO move to top of file or somewhere better
1294 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1295 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1298 * Uploads an image to Friendica.
1301 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1303 function api_media_upload()
1307 if (api_user() === false) {
1309 throw new ForbiddenException();
1314 if (!x($_FILES, 'media')) {
1316 throw new BadRequestException("No media.");
1319 $media = wall_upload_post($a, false);
1322 throw new InternalServerErrorException();
1326 $returndata["media_id"] = $media["id"];
1327 $returndata["media_id_string"] = (string)$media["id"];
1328 $returndata["size"] = $media["size"];
1329 $returndata["image"] = ["w" => $media["width"],
1330 "h" => $media["height"],
1331 "image_type" => $media["type"]];
1333 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1335 return ["media" => $returndata];
1338 /// @TODO move to top of file or somewhere better
1339 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1343 * @param string $type Return type (atom, rss, xml, json)
1345 * @return array|string
1347 function api_status_show($type)
1351 $user_info = api_get_user($a);
1353 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1355 if ($type == "raw") {
1356 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1361 // get last public wall message
1365 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1366 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1367 AND `item`.`type` != 'activity' $privacy_sql
1368 ORDER BY `item`.`id` DESC
1370 intval($user_info['cid']),
1372 dbesc($user_info['url']),
1373 dbesc(normalise_link($user_info['url'])),
1374 dbesc($user_info['url']),
1375 dbesc(normalise_link($user_info['url']))
1378 if (DBM::is_result($lastwall)) {
1379 $lastwall = $lastwall[0];
1381 $in_reply_to = api_in_reply_to($lastwall);
1383 $converted = api_convert_item($lastwall);
1385 if ($type == "xml") {
1386 $geo = "georss:point";
1392 'created_at' => api_date($lastwall['created']),
1393 'id' => intval($lastwall['id']),
1394 'id_str' => (string) $lastwall['id'],
1395 'text' => $converted["text"],
1396 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1397 'truncated' => false,
1398 'in_reply_to_status_id' => $in_reply_to['status_id'],
1399 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1400 'in_reply_to_user_id' => $in_reply_to['user_id'],
1401 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1402 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1403 'user' => $user_info,
1405 'coordinates' => "",
1407 'contributors' => "",
1408 'is_quote_status' => false,
1409 'retweet_count' => 0,
1410 'favorite_count' => 0,
1411 'favorited' => $lastwall['starred'] ? true : false,
1412 'retweeted' => false,
1413 'possibly_sensitive' => false,
1415 'statusnet_html' => $converted["html"],
1416 'statusnet_conversation_id' => $lastwall['parent'],
1417 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1420 if (count($converted["attachments"]) > 0) {
1421 $status_info["attachments"] = $converted["attachments"];
1424 if (count($converted["entities"]) > 0) {
1425 $status_info["entities"] = $converted["entities"];
1428 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1429 $status_info["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1430 } elseif (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1431 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['item_network'], $user_info['url']).')');
1434 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1435 unset($status_info["user"]["uid"]);
1436 unset($status_info["user"]["self"]);
1439 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1441 if ($type == "raw") {
1442 return $status_info;
1445 return api_format_data("statuses", $type, ['status' => $status_info]);
1449 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1450 * The author's most recent status will be returned inline.
1452 * @param string $type Return type (atom, rss, xml, json)
1453 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1455 function api_users_show($type)
1459 $user_info = api_get_user($a);
1463 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1464 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1465 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1466 AND `type`!='activity'
1467 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1471 dbesc(ACTIVITY_POST),
1472 intval($user_info['cid']),
1473 dbesc($user_info['url']),
1474 dbesc(normalise_link($user_info['url'])),
1475 dbesc($user_info['url']),
1476 dbesc(normalise_link($user_info['url']))
1479 if (DBM::is_result($lastwall)) {
1480 $lastwall = $lastwall[0];
1482 $in_reply_to = api_in_reply_to($lastwall);
1484 $converted = api_convert_item($lastwall);
1486 if ($type == "xml") {
1487 $geo = "georss:point";
1492 $user_info['status'] = [
1493 'text' => $converted["text"],
1494 'truncated' => false,
1495 'created_at' => api_date($lastwall['created']),
1496 'in_reply_to_status_id' => $in_reply_to['status_id'],
1497 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1498 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1499 'id' => intval($lastwall['contact-id']),
1500 'id_str' => (string) $lastwall['contact-id'],
1501 'in_reply_to_user_id' => $in_reply_to['user_id'],
1502 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1503 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1505 'favorited' => $lastwall['starred'] ? true : false,
1506 'statusnet_html' => $converted["html"],
1507 'statusnet_conversation_id' => $lastwall['parent'],
1508 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1511 if (count($converted["attachments"]) > 0) {
1512 $user_info["status"]["attachments"] = $converted["attachments"];
1515 if (count($converted["entities"]) > 0) {
1516 $user_info["status"]["entities"] = $converted["entities"];
1519 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1520 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1523 if (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1524 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) . ')');
1528 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1529 unset($user_info["uid"]);
1530 unset($user_info["self"]);
1532 return api_format_data("user", $type, ['user' => $user_info]);
1535 /// @TODO move to top of file or somewhere better
1536 api_register_func('api/users/show', 'api_users_show');
1537 api_register_func('api/externalprofile/show', 'api_users_show');
1540 * Search a public user account.
1542 * @param string $type Return type (atom, rss, xml, json)
1544 * @return array|string
1545 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1547 function api_users_search($type)
1553 if (x($_GET, 'q')) {
1554 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1556 if (!DBM::is_result($r)) {
1557 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1560 if (DBM::is_result($r)) {
1562 foreach ($r as $user) {
1563 $user_info = api_get_user($a, $user["id"]);
1565 if ($type == "xml") {
1566 $userlist[$k++.":user"] = $user_info;
1568 $userlist[] = $user_info;
1571 $userlist = ["users" => $userlist];
1573 throw new BadRequestException("User not found.");
1576 throw new BadRequestException("User not found.");
1579 return api_format_data("users", $type, $userlist);
1582 /// @TODO move to top of file or somewhere better
1583 api_register_func('api/users/search', 'api_users_search');
1586 * Return user objects
1588 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1590 * @param string $type Return format: json or xml
1592 * @return array|string
1593 * @throws NotFoundException if the results are empty.
1595 function api_users_lookup($type)
1599 if (x($_REQUEST['user_id'])) {
1600 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1602 $users[] = api_get_user(get_app(), $id);
1607 if (empty($users)) {
1608 throw new NotFoundException;
1611 return api_format_data("users", $type, ['users' => $users]);
1614 /// @TODO move to top of file or somewhere better
1615 api_register_func('api/users/lookup', 'api_users_lookup', true);
1618 * Returns statuses that match a specified query.
1620 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1622 * @param string $type Return format: json, xml, atom, rss
1624 * @return array|string
1625 * @throws BadRequestException if the "q" parameter is missing.
1627 function api_search($type)
1632 if (!x($_REQUEST, 'q')) {
1633 throw new BadRequestException("q parameter is required.");
1636 if (x($_REQUEST, 'rpp')) {
1637 $count = $_REQUEST['rpp'];
1638 } elseif (x($_REQUEST, 'count')) {
1639 $count = $_REQUEST['count'];
1644 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1645 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1646 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1648 $start = $page * $count;
1651 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1655 "SELECT ".item_fieldlists()."
1656 FROM `item` ".item_joins()."
1657 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1658 AND `item`.`body` LIKE CONCAT('%',?,'%')
1661 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1667 $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1669 return api_format_data("statuses", $type, $data);
1672 /// @TODO move to top of file or somewhere better
1673 api_register_func('api/search/tweets', 'api_search', true);
1674 api_register_func('api/search', 'api_search', true);
1677 * Returns the most recent statuses posted by the user and the users they follow.
1679 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1681 * @param string $type Return type (atom, rss, xml, json)
1683 * @todo Optional parameters
1684 * @todo Add reply info
1686 function api_statuses_home_timeline($type)
1690 if (api_user() === false) {
1691 throw new ForbiddenException();
1694 unset($_REQUEST["user_id"]);
1695 unset($_GET["user_id"]);
1697 unset($_REQUEST["screen_name"]);
1698 unset($_GET["screen_name"]);
1700 $user_info = api_get_user($a);
1701 // get last newtork messages
1704 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1705 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1709 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1710 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1711 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1712 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1713 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1715 $start = $page * $count;
1719 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1721 if ($exclude_replies > 0) {
1722 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1724 if ($conversation_id > 0) {
1725 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1729 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1730 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1731 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1732 `contact`.`id` AS `cid`
1734 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1735 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1736 WHERE `item`.`uid` = %d AND `verb` = '%s'
1737 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1740 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1742 dbesc(ACTIVITY_POST),
1748 $ret = api_format_items($r, $user_info, false, $type);
1750 // Set all posts from the query above to seen
1752 foreach ($r as $item) {
1753 $idarray[] = intval($item["id"]);
1756 $idlist = implode(",", $idarray);
1758 if ($idlist != "") {
1759 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1762 q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1766 $data = ['status' => $ret];
1770 $data = api_rss_extra($a, $data, $user_info);
1774 return api_format_data("statuses", $type, $data);
1777 /// @TODO move to top of file or somewhere better
1778 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1779 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1782 * Returns the most recent statuses from public users.
1784 * @param string $type Return type (atom, rss, xml, json)
1786 * @return array|string
1788 function api_statuses_public_timeline($type)
1792 if (api_user() === false) {
1793 throw new ForbiddenException();
1796 $user_info = api_get_user($a);
1797 // get last newtork messages
1800 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1801 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1805 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1806 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1807 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1808 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1809 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1811 $start = $page * $count;
1814 if ($exclude_replies && !$conversation_id) {
1816 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1820 "SELECT " . item_fieldlists() . "
1822 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1823 " . item_joins() . "
1824 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1825 AND NOT `user`.`hidewall`
1827 AND NOT `thread`.`private`
1829 AND `thread`.`visible`
1830 AND NOT `thread`.`deleted`
1831 AND NOT `thread`.`moderated`
1832 AND `thread`.`iid` > ?
1834 ORDER BY `thread`.`iid` DESC
1835 LIMIT " . intval($start) . ", " . intval($count),
1840 $r = dba::inArray($r);
1843 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1845 if ($conversation_id > 0) {
1846 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1850 "SELECT " . item_fieldlists() . "
1852 " . item_joins() . "
1853 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1854 AND NOT `user`.`hidewall`
1856 AND NOT `item`.`private`
1858 AND `item`.`visible`
1859 AND NOT `item`.`deleted`
1860 AND NOT `item`.`moderated`
1863 ORDER BY `item`.`id` DESC
1864 LIMIT " . intval($start) . ", " . intval($count),
1869 $r = dba::inArray($r);
1872 $ret = api_format_items($r, $user_info, false, $type);
1874 $data = ['status' => $ret];
1878 $data = api_rss_extra($a, $data, $user_info);
1882 return api_format_data("statuses", $type, $data);
1885 /// @TODO move to top of file or somewhere better
1886 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1889 * Returns the most recent statuses posted by users this node knows about.
1891 * @brief Returns the list of public federated posts this node knows about
1893 * @param string $type Return format: json, xml, atom, rss
1894 * @return array|string
1895 * @throws ForbiddenException
1897 function api_statuses_networkpublic_timeline($type)
1901 if (api_user() === false) {
1902 throw new ForbiddenException();
1905 $user_info = api_get_user($a);
1907 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1908 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1911 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1912 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1916 $start = ($page - 1) * $count;
1920 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1924 "SELECT " . item_fieldlists() . "
1926 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1927 " . item_joins() . "
1928 WHERE `thread`.`uid` = 0
1930 AND NOT `thread`.`private`
1931 AND `thread`.`visible`
1932 AND NOT `thread`.`deleted`
1933 AND NOT `thread`.`moderated`
1934 AND `thread`.`iid` > ?
1936 ORDER BY `thread`.`iid` DESC
1937 LIMIT " . intval($start) . ", " . intval($count),
1942 $r = dba::inArray($r);
1944 $ret = api_format_items($r, $user_info, false, $type);
1946 $data = ['status' => $ret];
1950 $data = api_rss_extra($a, $data, $user_info);
1954 return api_format_data("statuses", $type, $data);
1957 /// @TODO move to top of file or somewhere better
1958 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1961 * Returns a single status.
1963 * @param string $type Return type (atom, rss, xml, json)
1965 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1967 function api_statuses_show($type)
1971 if (api_user() === false) {
1972 throw new ForbiddenException();
1975 $user_info = api_get_user($a);
1978 $id = intval($a->argv[3]);
1981 $id = intval($_REQUEST["id"]);
1986 $id = intval($a->argv[4]);
1989 logger('API: api_statuses_show: ' . $id);
1991 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1994 if ($conversation) {
1995 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1997 $sql_extra .= " AND `item`.`id` = %d";
2001 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2002 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2003 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2004 `contact`.`id` AS `cid`
2006 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2007 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2008 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2009 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2012 dbesc(ACTIVITY_POST),
2016 /// @TODO How about copying this to above methods which don't check $r ?
2017 if (!DBM::is_result($r)) {
2018 throw new BadRequestException("There is no status with this id.");
2021 $ret = api_format_items($r, $user_info, false, $type);
2023 if ($conversation) {
2024 $data = ['status' => $ret];
2025 return api_format_data("statuses", $type, $data);
2027 $data = ['status' => $ret[0]];
2028 return api_format_data("status", $type, $data);
2032 /// @TODO move to top of file or somewhere better
2033 api_register_func('api/statuses/show', 'api_statuses_show', true);
2037 * @param string $type Return type (atom, rss, xml, json)
2039 * @todo nothing to say?
2041 function api_conversation_show($type)
2045 if (api_user() === false) {
2046 throw new ForbiddenException();
2049 $user_info = api_get_user($a);
2052 $id = intval($a->argv[3]);
2053 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2054 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
2058 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2059 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2061 $start = $page*$count;
2064 $id = intval($_REQUEST["id"]);
2069 $id = intval($a->argv[4]);
2072 logger('API: api_conversation_show: '.$id);
2074 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
2075 if (DBM::is_result($r)) {
2076 $id = $r[0]["parent"];
2082 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2085 // Not sure why this query was so complicated. We should keep it here for a while,
2086 // just to make sure that we really don't need it.
2087 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2088 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2091 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2092 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2093 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2094 `contact`.`id` AS `cid`
2096 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2097 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2098 WHERE `item`.`parent` = %d AND `item`.`visible`
2099 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2100 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2101 AND `item`.`id`>%d $sql_extra
2102 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2105 dbesc(ACTIVITY_POST),
2111 if (!DBM::is_result($r)) {
2112 throw new BadRequestException("There is no status with this id.");
2115 $ret = api_format_items($r, $user_info, false, $type);
2117 $data = ['status' => $ret];
2118 return api_format_data("statuses", $type, $data);
2121 /// @TODO move to top of file or somewhere better
2122 api_register_func('api/conversation/show', 'api_conversation_show', true);
2123 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2128 * @param string $type Return type (atom, rss, xml, json)
2130 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2132 function api_statuses_repeat($type)
2138 if (api_user() === false) {
2139 throw new ForbiddenException();
2145 $id = intval($a->argv[3]);
2148 $id = intval($_REQUEST["id"]);
2153 $id = intval($a->argv[4]);
2156 logger('API: api_statuses_repeat: '.$id);
2159 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2160 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2161 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2162 `contact`.`id` AS `cid`
2164 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2165 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2166 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2167 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2168 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2169 AND `item`.`id`=%d",
2173 /// @TODO other style than above functions!
2174 if (DBM::is_result($r) && $r[0]['body'] != "") {
2175 if (strpos($r[0]['body'], "[/share]") !== false) {
2176 $pos = strpos($r[0]['body'], "[share");
2177 $post = substr($r[0]['body'], $pos);
2179 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2181 $post .= $r[0]['body'];
2182 $post .= "[/share]";
2184 $_REQUEST['body'] = $post;
2185 $_REQUEST['profile_uid'] = api_user();
2186 $_REQUEST['type'] = 'wall';
2187 $_REQUEST['api_source'] = true;
2189 if (!x($_REQUEST, "source")) {
2190 $_REQUEST["source"] = api_source();
2195 throw new ForbiddenException();
2198 // this should output the last post (the one we just posted).
2200 return api_status_show($type);
2203 /// @TODO move to top of file or somewhere better
2204 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2207 * Destroys a specific status.
2209 * @param string $type Return type (atom, rss, xml, json)
2211 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2213 function api_statuses_destroy($type)
2217 if (api_user() === false) {
2218 throw new ForbiddenException();
2224 $id = intval($a->argv[3]);
2227 $id = intval($_REQUEST["id"]);
2232 $id = intval($a->argv[4]);
2235 logger('API: api_statuses_destroy: '.$id);
2237 $ret = api_statuses_show($type);
2239 Item::deleteById($id);
2244 /// @TODO move to top of file or somewhere better
2245 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2248 * Returns the most recent mentions.
2250 * @param string $type Return type (atom, rss, xml, json)
2252 * @see http://developer.twitter.com/doc/get/statuses/mentions
2254 function api_statuses_mentions($type)
2258 if (api_user() === false) {
2259 throw new ForbiddenException();
2262 unset($_REQUEST["user_id"]);
2263 unset($_GET["user_id"]);
2265 unset($_REQUEST["screen_name"]);
2266 unset($_GET["screen_name"]);
2268 $user_info = api_get_user($a);
2269 // get last newtork messages
2273 $since_id = defaults($_REQUEST, 'since_id', 0);
2274 $max_id = defaults($_REQUEST, 'max_id' , 0);
2275 $count = defaults($_REQUEST, 'count' , 20);
2276 $page = defaults($_REQUEST, 'page' , 1);
2281 $start = ($page - 1) * $count;
2283 // Ugly code - should be changed
2284 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2285 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2286 $myurl = str_replace('www.', '', $myurl);
2291 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2295 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2296 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2297 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2298 `contact`.`id` AS `cid`
2299 FROM `item` FORCE INDEX (`uid_id`)
2300 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2301 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2302 WHERE `item`.`uid` = %d AND `verb` = '%s'
2303 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2304 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2305 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2308 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2310 dbesc(ACTIVITY_POST),
2311 dbesc(protect_sprintf($myurl)),
2312 dbesc(protect_sprintf($myurl)),
2319 $ret = api_format_items($r, $user_info, false, $type);
2321 $data = ['status' => $ret];
2325 $data = api_rss_extra($a, $data, $user_info);
2329 return api_format_data("statuses", $type, $data);
2332 /// @TODO move to top of file or somewhere better
2333 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2334 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2337 * Returns the most recent statuses posted by the user.
2339 * @brief Returns a user's public timeline
2341 * @param string $type Either "json" or "xml"
2342 * @return string|array
2343 * @throws ForbiddenException
2344 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2346 function api_statuses_user_timeline($type)
2350 if (api_user() === false) {
2351 throw new ForbiddenException();
2354 $user_info = api_get_user($a);
2357 "api_statuses_user_timeline: api_user: ". api_user() .
2358 "\nuser_info: ".print_r($user_info, true) .
2359 "\n_REQUEST: ".print_r($_REQUEST, true),
2363 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2364 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2365 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2366 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2369 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2370 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2374 $start = ($page - 1) * $count;
2377 if ($user_info['self'] == 1) {
2378 $sql_extra .= " AND `item`.`wall` = 1 ";
2381 if ($exclude_replies > 0) {
2382 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2385 if ($conversation_id > 0) {
2386 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2390 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2394 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2395 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2396 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2397 `contact`.`id` AS `cid`
2398 FROM `item` FORCE INDEX (`uid_contactid_id`)
2399 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2400 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2401 WHERE `item`.`uid` = %d AND `verb` = '%s'
2402 AND `item`.`contact-id` = %d
2403 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2405 AND `item`.`id` > %d
2406 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2408 dbesc(ACTIVITY_POST),
2409 intval($user_info['cid']),
2415 $ret = api_format_items($r, $user_info, true, $type);
2417 $data = ['status' => $ret];
2421 $data = api_rss_extra($a, $data, $user_info);
2425 return api_format_data("statuses", $type, $data);
2428 /// @TODO move to top of file or somewhere better
2429 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2432 * Star/unstar an item.
2433 * param: id : id of the item
2435 * @param string $type Return type (atom, rss, xml, json)
2437 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2439 function api_favorites_create_destroy($type)
2443 if (api_user() === false) {
2444 throw new ForbiddenException();
2447 // for versioned api.
2448 /// @TODO We need a better global soluton
2449 $action_argv_id = 2;
2450 if ($a->argv[1] == "1.1") {
2451 $action_argv_id = 3;
2454 if ($a->argc <= $action_argv_id) {
2455 throw new BadRequestException("Invalid request.");
2457 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2458 if ($a->argc == $action_argv_id + 2) {
2459 $itemid = intval($a->argv[$action_argv_id + 1]);
2461 /// @TODO use x() to check if _REQUEST contains 'id'
2462 $itemid = intval($_REQUEST['id']);
2465 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2467 if (!DBM::is_result($item) || count($item) == 0) {
2468 throw new BadRequestException("Invalid item.");
2473 $item[0]['starred'] = 1;
2476 $item[0]['starred'] = 0;
2479 throw new BadRequestException("Invalid action ".$action);
2482 $r = Item::update(['starred' => $item[0]['starred']], ['id' => $itemid]);
2485 throw new InternalServerErrorException("DB error");
2489 $user_info = api_get_user($a);
2490 $rets = api_format_items($item, $user_info, false, $type);
2493 $data = ['status' => $ret];
2497 $data = api_rss_extra($a, $data, $user_info);
2500 return api_format_data("status", $type, $data);
2503 /// @TODO move to top of file or somewhere better
2504 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2505 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2508 * Returns the most recent favorite statuses.
2510 * @param string $type Return type (atom, rss, xml, json)
2512 * @return string|array
2514 function api_favorites($type)
2520 if (api_user() === false) {
2521 throw new ForbiddenException();
2526 $user_info = api_get_user($a);
2528 // in friendica starred item are private
2529 // return favorites only for self
2530 logger('api_favorites: self:' . $user_info['self']);
2532 if ($user_info['self'] == 0) {
2538 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2539 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2540 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2541 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2546 $start = $page*$count;
2549 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2553 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2554 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2555 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2556 `contact`.`id` AS `cid`
2557 FROM `item`, `contact`
2558 WHERE `item`.`uid` = %d
2559 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2560 AND `item`.`starred` = 1
2561 AND `contact`.`id` = `item`.`contact-id`
2562 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2565 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2572 $ret = api_format_items($r, $user_info, false, $type);
2575 $data = ['status' => $ret];
2579 $data = api_rss_extra($a, $data, $user_info);
2582 return api_format_data("statuses", $type, $data);
2585 /// @TODO move to top of file or somewhere better
2586 api_register_func('api/favorites', 'api_favorites', true);
2590 * @param array $item
2591 * @param array $recipient
2592 * @param array $sender
2596 function api_format_messages($item, $recipient, $sender)
2598 // standard meta information
2600 'id' => $item['id'],
2601 'sender_id' => $sender['id'] ,
2603 'recipient_id' => $recipient['id'],
2604 'created_at' => api_date($item['created']),
2605 'sender_screen_name' => $sender['screen_name'],
2606 'recipient_screen_name' => $recipient['screen_name'],
2607 'sender' => $sender,
2608 'recipient' => $recipient,
2610 'friendica_seen' => $item['seen'],
2611 'friendica_parent_uri' => $item['parent-uri'],
2614 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2615 unset($ret["sender"]["uid"]);
2616 unset($ret["sender"]["self"]);
2617 unset($ret["recipient"]["uid"]);
2618 unset($ret["recipient"]["self"]);
2620 //don't send title to regular StatusNET requests to avoid confusing these apps
2621 if (x($_GET, 'getText')) {
2622 $ret['title'] = $item['title'];
2623 if ($_GET['getText'] == 'html') {
2624 $ret['text'] = BBCode::convert($item['body'], false);
2625 } elseif ($_GET['getText'] == 'plain') {
2626 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2629 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2631 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2632 unset($ret['sender']);
2633 unset($ret['recipient']);
2641 * @param array $item
2645 function api_convert_item($item)
2647 $body = $item['body'];
2648 $attachments = api_get_attachments($body);
2650 // Workaround for ostatus messages where the title is identically to the body
2651 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2652 $statusbody = trim(HTML::toPlaintext($html, 0));
2654 // handle data: images
2655 $statusbody = api_format_items_embeded_images($item, $statusbody);
2657 $statustitle = trim($item['title']);
2659 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2660 $statustext = trim($statusbody);
2662 $statustext = trim($statustitle."\n\n".$statusbody);
2665 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2666 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2669 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2671 // Workaround for clients with limited HTML parser functionality
2672 $search = ["<br>", "<blockquote>", "</blockquote>",
2673 "<h1>", "</h1>", "<h2>", "</h2>",
2674 "<h3>", "</h3>", "<h4>", "</h4>",
2675 "<h5>", "</h5>", "<h6>", "</h6>"];
2676 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2677 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2678 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2679 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2680 $statushtml = str_replace($search, $replace, $statushtml);
2682 if ($item['title'] != "") {
2683 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2687 $oldtext = $statushtml;
2688 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2689 } while ($oldtext != $statushtml);
2691 if (substr($statushtml, 0, 4) == '<br>') {
2692 $statushtml = substr($statushtml, 4);
2695 if (substr($statushtml, 0, -4) == '<br>') {
2696 $statushtml = substr($statushtml, -4);
2699 // feeds without body should contain the link
2700 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2701 $statushtml .= BBCode::convert($item['plink']);
2704 $entities = api_get_entitities($statustext, $body);
2707 "text" => $statustext,
2708 "html" => $statushtml,
2709 "attachments" => $attachments,
2710 "entities" => $entities
2716 * @param string $body
2718 * @return array|false
2720 function api_get_attachments(&$body)
2723 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2725 $URLSearchString = "^\[\]";
2726 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2734 foreach ($images[1] as $image) {
2735 $imagedata = Image::getInfoFromURL($image);
2738 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2742 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2743 foreach ($images[0] as $orig) {
2744 $body = str_replace($orig, "", $body);
2748 return $attachments;
2753 * @param string $text
2754 * @param string $bbcode
2757 * @todo Links at the first character of the post
2759 function api_get_entitities(&$text, $bbcode)
2761 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2763 if ($include_entities != "true") {
2764 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2766 foreach ($images[1] as $image) {
2767 $replace = proxy_url($image);
2768 $text = str_replace($image, $replace, $text);
2773 $bbcode = BBCode::cleanPictureLinks($bbcode);
2775 // Change pure links in text to bbcode uris
2776 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2779 $entities["hashtags"] = [];
2780 $entities["symbols"] = [];
2781 $entities["urls"] = [];
2782 $entities["user_mentions"] = [];
2784 $URLSearchString = "^\[\]";
2786 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2788 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2789 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2790 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2792 $bbcode = preg_replace(
2793 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2794 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2797 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2799 $bbcode = preg_replace(
2800 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2801 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2804 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2806 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2808 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2809 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2812 foreach ($urls[1] as $id => $url) {
2813 //$start = strpos($text, $url, $offset);
2814 $start = iconv_strpos($text, $url, 0, "UTF-8");
2815 if (!($start === false)) {
2816 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2820 ksort($ordered_urls);
2823 //foreach ($urls[1] AS $id=>$url) {
2824 foreach ($ordered_urls as $url) {
2825 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2826 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2828 $display_url = $url["title"];
2830 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2831 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2833 if (strlen($display_url) > 26) {
2834 $display_url = substr($display_url, 0, 25)."…";
2838 //$start = strpos($text, $url, $offset);
2839 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2840 if (!($start === false)) {
2841 $entities["urls"][] = ["url" => $url["url"],
2842 "expanded_url" => $url["url"],
2843 "display_url" => $display_url,
2844 "indices" => [$start, $start+strlen($url["url"])]];
2845 $offset = $start + 1;
2849 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2850 $ordered_images = [];
2851 foreach ($images[1] as $image) {
2852 //$start = strpos($text, $url, $offset);
2853 $start = iconv_strpos($text, $image, 0, "UTF-8");
2854 if (!($start === false)) {
2855 $ordered_images[$start] = $image;
2858 //$entities["media"] = array();
2861 foreach ($ordered_images as $url) {
2862 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2863 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2865 if (strlen($display_url) > 26) {
2866 $display_url = substr($display_url, 0, 25)."…";
2869 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2870 if (!($start === false)) {
2871 $image = Image::getInfoFromURL($url);
2873 // If image cache is activated, then use the following sizes:
2874 // thumb (150), small (340), medium (600) and large (1024)
2875 if (!Config::get("system", "proxy_disabled")) {
2876 $media_url = proxy_url($url);
2879 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2880 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2882 if (($image[0] > 150) || ($image[1] > 150)) {
2883 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2884 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2887 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2888 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2890 if (($image[0] > 600) || ($image[1] > 600)) {
2891 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2892 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2896 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2899 $entities["media"][] = [
2901 "id_str" => (string)$start+1,
2902 "indices" => [$start, $start+strlen($url)],
2903 "media_url" => normalise_link($media_url),
2904 "media_url_https" => $media_url,
2906 "display_url" => $display_url,
2907 "expanded_url" => $url,
2911 $offset = $start + 1;
2920 * @param array $item
2921 * @param string $text
2925 function api_format_items_embeded_images($item, $text)
2927 $text = preg_replace_callback(
2928 '|data:image/([^;]+)[^=]+=*|m',
2929 function () use ($item) {
2930 return System::baseUrl() . '/display/' . $item['guid'];
2938 * @brief return <a href='url'>name</a> as array
2940 * @param string $txt text
2945 function api_contactlink_to_array($txt)
2948 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2949 if ($r && count($match)==3) {
2951 'name' => $match[2],
2965 * @brief return likes, dislikes and attend status for item
2967 * @param array $item array
2968 * @param string $type Return type (atom, rss, xml, json)
2971 * likes => int count,
2972 * dislikes => int count
2974 function api_format_items_activities(&$item, $type = "json")
2983 'attendmaybe' => [],
2988 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2989 intval($item['uid']),
2993 foreach ($items as $i) {
2994 // not used as result should be structured like other user data
2995 //builtin_activity_puller($i, $activities);
2997 // get user data and add it to the array of the activity
2998 $user = api_get_user($a, $i['author-link']);
2999 switch ($i['verb']) {
3001 $activities['like'][] = $user;
3003 case ACTIVITY_DISLIKE:
3004 $activities['dislike'][] = $user;
3006 case ACTIVITY_ATTEND:
3007 $activities['attendyes'][] = $user;
3009 case ACTIVITY_ATTENDNO:
3010 $activities['attendno'][] = $user;
3012 case ACTIVITY_ATTENDMAYBE:
3013 $activities['attendmaybe'][] = $user;
3020 if ($type == "xml") {
3021 $xml_activities = [];
3022 foreach ($activities as $k => $v) {
3023 // change xml element from "like" to "friendica:like"
3024 $xml_activities["friendica:".$k] = $v;
3025 // add user data into xml output
3027 foreach ($v as $user) {
3028 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
3031 $activities = $xml_activities;
3039 * @brief return data from profiles
3041 * @param array $profile_row array containing data from db table 'profile'
3044 function api_format_items_profiles($profile_row)
3047 'profile_id' => $profile_row['id'],
3048 'profile_name' => $profile_row['profile-name'],
3049 'is_default' => $profile_row['is-default'] ? true : false,
3050 'hide_friends' => $profile_row['hide-friends'] ? true : false,
3051 'profile_photo' => $profile_row['photo'],
3052 'profile_thumb' => $profile_row['thumb'],
3053 'publish' => $profile_row['publish'] ? true : false,
3054 'net_publish' => $profile_row['net-publish'] ? true : false,
3055 'description' => $profile_row['pdesc'],
3056 'date_of_birth' => $profile_row['dob'],
3057 'address' => $profile_row['address'],
3058 'city' => $profile_row['locality'],
3059 'region' => $profile_row['region'],
3060 'postal_code' => $profile_row['postal-code'],
3061 'country' => $profile_row['country-name'],
3062 'hometown' => $profile_row['hometown'],
3063 'gender' => $profile_row['gender'],
3064 'marital' => $profile_row['marital'],
3065 'marital_with' => $profile_row['with'],
3066 'marital_since' => $profile_row['howlong'],
3067 'sexual' => $profile_row['sexual'],
3068 'politic' => $profile_row['politic'],
3069 'religion' => $profile_row['religion'],
3070 'public_keywords' => $profile_row['pub_keywords'],
3071 'private_keywords' => $profile_row['prv_keywords'],
3072 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
3073 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
3074 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
3075 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
3076 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
3077 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
3078 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
3079 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
3080 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
3081 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
3082 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
3083 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
3084 'homepage' => $profile_row['homepage'],
3091 * @brief format items to be returned by api
3093 * @param array $r array of items
3094 * @param array $user_info
3095 * @param bool $filter_user filter items by $user_info
3096 * @param string $type Return type (atom, rss, xml, json)
3098 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3104 foreach ($r as $item) {
3105 localize_item($item);
3106 list($status_user, $owner_user) = api_item_get_user($a, $item);
3108 // Look if the posts are matching if they should be filtered by user id
3109 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3113 $in_reply_to = api_in_reply_to($item);
3115 $converted = api_convert_item($item);
3117 if ($type == "xml") {
3118 $geo = "georss:point";
3124 'text' => $converted["text"],
3125 'truncated' => false,
3126 'created_at'=> api_date($item['created']),
3127 'in_reply_to_status_id' => $in_reply_to['status_id'],
3128 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3129 'source' => (($item['app']) ? $item['app'] : 'web'),
3130 'id' => intval($item['id']),
3131 'id_str' => (string) intval($item['id']),
3132 'in_reply_to_user_id' => $in_reply_to['user_id'],
3133 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3134 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3136 'favorited' => $item['starred'] ? true : false,
3137 'user' => $status_user ,
3138 'friendica_owner' => $owner_user,
3139 //'entities' => NULL,
3140 'statusnet_html' => $converted["html"],
3141 'statusnet_conversation_id' => $item['parent'],
3142 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3143 'friendica_activities' => api_format_items_activities($item, $type),
3146 if (count($converted["attachments"]) > 0) {
3147 $status["attachments"] = $converted["attachments"];
3150 if (count($converted["entities"]) > 0) {
3151 $status["entities"] = $converted["entities"];
3154 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3155 $status["source"] = ContactSelector::networkToName($item['item_network'], $user_info['url']);
3156 } elseif (($item['item_network'] != "") && (ContactSelector::networkToName($item['item_network'], $user_info['url']) != $status["source"])) {
3157 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['item_network'], $user_info['url']).')');
3161 // Retweets are only valid for top postings
3162 // It doesn't work reliable with the link if its a feed
3163 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3165 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3168 if ($item["id"] == $item["parent"]) {
3169 $retweeted_item = api_share_as_retweet($item);
3170 if ($retweeted_item !== false) {
3171 $retweeted_status = $status;
3173 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3174 } catch (BadRequestException $e) {
3175 // user not found. should be found?
3176 /// @todo check if the user should be always found
3177 $retweeted_status["user"] = [];
3180 $rt_converted = api_convert_item($retweeted_item);
3182 $retweeted_status['text'] = $rt_converted["text"];
3183 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3184 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3185 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3186 $status['retweeted_status'] = $retweeted_status;
3190 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3191 unset($status["user"]["uid"]);
3192 unset($status["user"]["self"]);
3194 if ($item["coord"] != "") {
3195 $coords = explode(' ', $item["coord"]);
3196 if (count($coords) == 2) {
3197 if ($type == "json") {
3198 $status["geo"] = ['type' => 'Point',
3199 'coordinates' => [(float) $coords[0],
3200 (float) $coords[1]]];
3201 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3202 $status["georss:point"] = $item["coord"];
3212 * Returns the remaining number of API requests available to the user before the API limit is reached.
3214 * @param string $type Return type (atom, rss, xml, json)
3216 * @return array|string
3218 function api_account_rate_limit_status($type)
3220 if ($type == "xml") {
3222 'remaining-hits' => '150',
3223 '@attributes' => ["type" => "integer"],
3224 'hourly-limit' => '150',
3225 '@attributes2' => ["type" => "integer"],
3226 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3227 '@attributes3' => ["type" => "datetime"],
3228 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3229 '@attributes4' => ["type" => "integer"],
3233 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3234 'remaining_hits' => '150',
3235 'hourly_limit' => '150',
3236 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3240 return api_format_data('hash', $type, ['hash' => $hash]);
3243 /// @TODO move to top of file or somewhere better
3244 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3247 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3249 * @param string $type Return type (atom, rss, xml, json)
3251 * @return array|string
3253 function api_help_test($type)
3255 if ($type == 'xml') {
3261 return api_format_data('ok', $type, ["ok" => $ok]);
3264 /// @TODO move to top of file or somewhere better
3265 api_register_func('api/help/test', 'api_help_test', false);
3269 * @param string $type Return type (atom, rss, xml, json)
3271 * @return array|string
3273 function api_lists($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', 'api_lists', true);
3284 * Returns all lists the user subscribes to.
3286 * @param string $type Return type (atom, rss, xml, json)
3288 * @return array|string
3289 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3291 function api_lists_list($type)
3294 /// @TODO $ret is not filled here?
3295 return api_format_data('lists', $type, ["lists_list" => $ret]);
3298 /// @TODO move to top of file or somewhere better
3299 api_register_func('api/lists/list', 'api_lists_list', true);
3302 * Considers friends and followers lists to be private and won't return
3303 * anything if any user_id parameter is passed.
3305 * @brief Returns either the friends of the follower list
3307 * @param string $qtype Either "friends" or "followers"
3308 * @return boolean|array
3309 * @throws ForbiddenException
3311 function api_statuses_f($qtype)
3315 if (api_user() === false) {
3316 throw new ForbiddenException();
3320 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3321 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3325 $start = ($page - 1) * $count;
3327 $user_info = api_get_user($a);
3329 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3330 /* this is to stop Hotot to load friends multiple times
3331 * I'm not sure if I'm missing return something or
3332 * is a bug in hotot. Workaround, meantime
3336 return array('$users' => $ret);*/
3341 if ($qtype == 'friends') {
3342 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3343 } elseif ($qtype == 'followers') {
3344 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3347 // friends and followers only for self
3348 if ($user_info['self'] == 0) {
3349 $sql_extra = " AND false ";
3352 if ($qtype == 'blocks') {
3353 $sql_filter = 'AND `blocked` AND NOT `pending`';
3354 } elseif ($qtype == 'incoming') {
3355 $sql_filter = 'AND `pending`';
3357 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3375 foreach ($r as $cid) {
3376 $user = api_get_user($a, $cid['nurl']);
3377 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3378 unset($user["uid"]);
3379 unset($user["self"]);
3386 return ['user' => $ret];
3391 * Returns the user's friends.
3393 * @brief Returns the list of friends of the provided user
3395 * @deprecated By Twitter API in favor of friends/list
3397 * @param string $type Either "json" or "xml"
3398 * @return boolean|string|array
3400 function api_statuses_friends($type)
3402 $data = api_statuses_f("friends");
3403 if ($data === false) {
3406 return api_format_data("users", $type, $data);
3410 * Returns the user's followers.
3412 * @brief Returns the list of followers of the provided user
3414 * @deprecated By Twitter API in favor of friends/list
3416 * @param string $type Either "json" or "xml"
3417 * @return boolean|string|array
3419 function api_statuses_followers($type)
3421 $data = api_statuses_f("followers");
3422 if ($data === false) {
3425 return api_format_data("users", $type, $data);
3428 /// @TODO move to top of file or somewhere better
3429 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3430 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3433 * Returns the list of blocked users
3435 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3437 * @param string $type Either "json" or "xml"
3439 * @return boolean|string|array
3441 function api_blocks_list($type)
3443 $data = api_statuses_f('blocks');
3444 if ($data === false) {
3447 return api_format_data("users", $type, $data);
3450 /// @TODO move to top of file or somewhere better
3451 api_register_func('api/blocks/list', 'api_blocks_list', true);
3454 * Returns the list of pending users IDs
3456 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3458 * @param string $type Either "json" or "xml"
3460 * @return boolean|string|array
3462 function api_friendships_incoming($type)
3464 $data = api_statuses_f('incoming');
3465 if ($data === false) {
3470 foreach ($data['user'] as $user) {
3471 $ids[] = $user['id'];
3474 return api_format_data("ids", $type, ['id' => $ids]);
3477 /// @TODO move to top of file or somewhere better
3478 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3481 * Returns the instance's configuration information.
3483 * @param string $type Return type (atom, rss, xml, json)
3485 * @return array|string
3487 function api_statusnet_config($type)
3491 $name = $a->config['sitename'];
3492 $server = $a->get_hostname();
3493 $logo = System::baseUrl() . '/images/friendica-64.png';
3494 $email = $a->config['admin_email'];
3495 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3496 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3497 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3498 if ($a->config['api_import_size']) {
3499 $textlimit = (string) $a->config['api_import_size'];
3501 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3502 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3505 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3506 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3507 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3508 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3509 'shorturllength' => '30',
3511 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3512 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3513 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3514 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3519 return api_format_data('config', $type, ['config' => $config]);
3522 /// @TODO move to top of file or somewhere better
3523 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3524 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3528 * @param string $type Return type (atom, rss, xml, json)
3530 * @return array|string
3532 function api_statusnet_version($type)
3535 $fake_statusnet_version = "0.9.7";
3537 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3540 /// @TODO move to top of file or somewhere better
3541 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3542 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3546 * @param string $type Return type (atom, rss, xml, json)
3548 * @todo use api_format_data() to return data
3550 function api_ff_ids($type)
3553 throw new ForbiddenException();
3560 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3563 "SELECT `pcontact`.`id` FROM `contact`
3564 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3565 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3568 if (!DBM::is_result($r)) {
3573 foreach ($r as $rr) {
3574 if ($stringify_ids) {
3577 $ids[] = intval($rr['id']);
3581 return api_format_data("ids", $type, ['id' => $ids]);
3585 * Returns the ID of every user the user is following.
3587 * @param string $type Return type (atom, rss, xml, json)
3589 * @return array|string
3590 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3592 function api_friends_ids($type)
3594 return api_ff_ids($type);
3598 * Returns the ID of every user following the user.
3600 * @param string $type Return type (atom, rss, xml, json)
3602 * @return array|string
3603 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3605 function api_followers_ids($type)
3607 return api_ff_ids($type);
3610 /// @TODO move to top of file or somewhere better
3611 api_register_func('api/friends/ids', 'api_friends_ids', true);
3612 api_register_func('api/followers/ids', 'api_followers_ids', true);
3615 * Sends a new direct message.
3617 * @param string $type Return type (atom, rss, xml, json)
3619 * @return array|string
3620 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3622 function api_direct_messages_new($type)
3627 if (api_user() === false) {
3628 throw new ForbiddenException();
3631 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3635 $sender = api_get_user($a);
3637 if ($_POST['screen_name']) {
3639 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3641 dbesc($_POST['screen_name'])
3644 // Selecting the id by priority, friendica first
3645 api_best_nickname($r);
3647 $recipient = api_get_user($a, $r[0]['nurl']);
3649 $recipient = api_get_user($a, $_POST['user_id']);
3654 if (x($_REQUEST, 'replyto')) {
3656 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3658 intval($_REQUEST['replyto'])
3660 $replyto = $r[0]['parent-uri'];
3661 $sub = $r[0]['title'];
3663 if (x($_REQUEST, 'title')) {
3664 $sub = $_REQUEST['title'];
3666 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3670 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3673 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3674 $ret = api_format_messages($r[0], $recipient, $sender);
3676 $ret = ["error"=>$id];
3679 $data = ['direct_message'=>$ret];
3684 $data = api_rss_extra($a, $data, $sender);
3687 return api_format_data("direct-messages", $type, $data);
3690 /// @TODO move to top of file or somewhere better
3691 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3694 * Destroys a direct message.
3696 * @brief delete a direct_message from mail table through api
3698 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3700 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3702 function api_direct_messages_destroy($type)
3706 if (api_user() === false) {
3707 throw new ForbiddenException();
3711 $user_info = api_get_user($a);
3713 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3715 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3716 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3717 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3719 $uid = $user_info['uid'];
3720 // error if no id or parenturi specified (for clients posting parent-uri as well)
3721 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3722 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3723 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3726 // BadRequestException if no id specified (for clients using Twitter API)
3728 throw new BadRequestException('Message id not specified');
3731 // add parent-uri to sql command if specified by calling app
3732 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3734 // get data of the specified message id
3736 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3741 // error message if specified id is not in database
3742 if (!DBM::is_result($r)) {
3743 if ($verbose == "true") {
3744 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3745 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3747 /// @todo BadRequestException ok for Twitter API clients?
3748 throw new BadRequestException('message id not in database');
3753 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3758 if ($verbose == "true") {
3761 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3762 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3764 $answer = ['result' => 'error', 'message' => 'unknown error'];
3765 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3768 /// @todo return JSON data like Twitter API not yet implemented
3771 /// @TODO move to top of file or somewhere better
3772 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3776 * @param string $type Return type (atom, rss, xml, json)
3777 * @param string $box
3778 * @param string $verbose
3780 * @return array|string
3782 function api_direct_messages_box($type, $box, $verbose)
3786 if (api_user() === false) {
3787 throw new ForbiddenException();
3791 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3792 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3797 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3798 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3800 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3801 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3804 unset($_REQUEST["user_id"]);
3805 unset($_GET["user_id"]);
3807 unset($_REQUEST["screen_name"]);
3808 unset($_GET["screen_name"]);
3810 $user_info = api_get_user($a);
3811 $profile_url = $user_info["url"];
3814 $start = $page * $count;
3819 if ($box=="sentbox") {
3820 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3821 } elseif ($box == "conversation") {
3822 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3823 } elseif ($box == "all") {
3824 $sql_extra = "true";
3825 } elseif ($box == "inbox") {
3826 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3830 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3833 if ($user_id != "") {
3834 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3835 } elseif ($screen_name !="") {
3836 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3840 "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",
3846 if ($verbose == "true" && !DBM::is_result($r)) {
3847 $answer = ['result' => 'error', 'message' => 'no mails available'];
3848 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3852 foreach ($r as $item) {
3853 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3854 $recipient = $user_info;
3855 $sender = api_get_user($a, normalise_link($item['contact-url']));
3856 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3857 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3858 $sender = $user_info;
3861 $ret[] = api_format_messages($item, $recipient, $sender);
3865 $data = ['direct_message' => $ret];
3869 $data = api_rss_extra($a, $data, $user_info);
3872 return api_format_data("direct-messages", $type, $data);
3876 * Returns the most recent direct messages sent by the user.
3878 * @param string $type Return type (atom, rss, xml, json)
3880 * @return array|string
3881 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3883 function api_direct_messages_sentbox($type)
3885 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3886 return api_direct_messages_box($type, "sentbox", $verbose);
3890 * Returns the most recent direct messages sent to the user.
3892 * @param string $type Return type (atom, rss, xml, json)
3894 * @return array|string
3895 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3897 function api_direct_messages_inbox($type)
3899 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3900 return api_direct_messages_box($type, "inbox", $verbose);
3905 * @param string $type Return type (atom, rss, xml, json)
3907 * @return array|string
3909 function api_direct_messages_all($type)
3911 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3912 return api_direct_messages_box($type, "all", $verbose);
3917 * @param string $type Return type (atom, rss, xml, json)
3919 * @return array|string
3921 function api_direct_messages_conversation($type)
3923 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3924 return api_direct_messages_box($type, "conversation", $verbose);
3927 /// @TODO move to top of file or somewhere better
3928 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3929 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3930 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3931 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3934 * Returns an OAuth Request Token.
3936 * @see https://oauth.net/core/1.0/#auth_step1
3938 function api_oauth_request_token()
3940 $oauth1 = new FKOAuth1();
3942 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3943 } catch (Exception $e) {
3944 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3952 * Returns an OAuth Access Token.
3954 * @return array|string
3955 * @see https://oauth.net/core/1.0/#auth_step3
3957 function api_oauth_access_token()
3959 $oauth1 = new FKOAuth1();
3961 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3962 } catch (Exception $e) {
3963 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3970 /// @TODO move to top of file or somewhere better
3971 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3972 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3976 * @brief delete a complete photoalbum with all containing photos from database through api
3978 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3981 function api_fr_photoalbum_delete($type)
3983 if (api_user() === false) {
3984 throw new ForbiddenException();
3987 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3989 // we do not allow calls without album string
3991 throw new BadRequestException("no albumname specified");
3993 // check if album is existing
3995 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3999 if (!DBM::is_result($r)) {
4000 throw new BadRequestException("album not available");
4003 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4004 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4005 foreach ($r as $rr) {
4007 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4008 intval(local_user()),
4009 dbesc($rr['resource-id'])
4012 if (!DBM::is_result($photo_item)) {
4013 throw new InternalServerErrorException("problem with deleting items occured");
4015 Item::deleteById($photo_item[0]['id']);
4018 // now let's delete all photos from the album
4019 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
4021 // return success of deletion or error message
4023 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4024 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4026 throw new InternalServerErrorException("unknown error - deleting from database failed");
4031 * @brief update the name of the album for all photos of an album
4033 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4036 function api_fr_photoalbum_update($type)
4038 if (api_user() === false) {
4039 throw new ForbiddenException();
4042 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4043 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4045 // we do not allow calls without album string
4047 throw new BadRequestException("no albumname specified");
4049 if ($album_new == "") {
4050 throw new BadRequestException("no new albumname specified");
4052 // check if album is existing
4054 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4058 if (!DBM::is_result($r)) {
4059 throw new BadRequestException("album not available");
4061 // now let's update all photos to the albumname
4063 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
4069 // return success of updating or error message
4071 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4072 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4074 throw new InternalServerErrorException("unknown error - updating in database failed");
4080 * @brief list all photos of the authenticated user
4082 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4085 function api_fr_photos_list($type)
4087 if (api_user() === false) {
4088 throw new ForbiddenException();
4091 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4092 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4093 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4094 intval(local_user())
4097 'image/jpeg' => 'jpg',
4098 'image/png' => 'png',
4099 'image/gif' => 'gif'
4101 $data = ['photo'=>[]];
4102 if (DBM::is_result($r)) {
4103 foreach ($r as $rr) {
4105 $photo['id'] = $rr['resource-id'];
4106 $photo['album'] = $rr['album'];
4107 $photo['filename'] = $rr['filename'];
4108 $photo['type'] = $rr['type'];
4109 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4110 $photo['created'] = $rr['created'];
4111 $photo['edited'] = $rr['edited'];
4112 $photo['desc'] = $rr['desc'];
4114 if ($type == "xml") {
4115 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4117 $photo['thumb'] = $thumb;
4118 $data['photo'][] = $photo;
4122 return api_format_data("photos", $type, $data);
4126 * @brief upload a new photo or change an existing photo
4128 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4131 function api_fr_photo_create_update($type)
4133 if (api_user() === false) {
4134 throw new ForbiddenException();
4137 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4138 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4139 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4140 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4141 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4142 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4143 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4144 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4145 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4147 // do several checks on input parameters
4148 // we do not allow calls without album string
4149 if ($album == null) {
4150 throw new BadRequestException("no albumname specified");
4152 // if photo_id == null --> we are uploading a new photo
4153 if ($photo_id == null) {
4156 // error if no media posted in create-mode
4157 if (!x($_FILES, 'media')) {
4159 throw new BadRequestException("no media data submitted");
4162 // album_new will be ignored in create-mode
4167 // check if photo is existing in database
4169 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4174 if (!DBM::is_result($r)) {
4175 throw new BadRequestException("photo not available");
4179 // checks on acl strings provided by clients
4180 $acl_input_error = false;
4181 $acl_input_error |= check_acl_input($allow_cid);
4182 $acl_input_error |= check_acl_input($deny_cid);
4183 $acl_input_error |= check_acl_input($allow_gid);
4184 $acl_input_error |= check_acl_input($deny_gid);
4185 if ($acl_input_error) {
4186 throw new BadRequestException("acl data invalid");
4188 // now let's upload the new media in create-mode
4189 if ($mode == "create") {
4190 $media = $_FILES['media'];
4191 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4193 // return success of updating or error message
4194 if (!is_null($data)) {
4195 return api_format_data("photo_create", $type, $data);
4197 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4201 // now let's do the changes in update-mode
4202 if ($mode == "update") {
4205 if (!is_null($desc)) {
4206 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4209 if (!is_null($album_new)) {
4210 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4213 if (!is_null($allow_cid)) {
4214 $allow_cid = trim($allow_cid);
4215 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4218 if (!is_null($deny_cid)) {
4219 $deny_cid = trim($deny_cid);
4220 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4223 if (!is_null($allow_gid)) {
4224 $allow_gid = trim($allow_gid);
4225 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4228 if (!is_null($deny_gid)) {
4229 $deny_gid = trim($deny_gid);
4230 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4234 if ($sql_extra != "") {
4235 $nothingtodo = false;
4237 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4239 DateTimeFormat::utcNow(), // update edited timestamp
4245 $nothingtodo = true;
4248 if (x($_FILES, 'media')) {
4249 $nothingtodo = false;
4250 $media = $_FILES['media'];
4251 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4252 if (!is_null($data)) {
4253 return api_format_data("photo_update", $type, $data);
4257 // return success of updating or error message
4259 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4260 return api_format_data("photo_update", $type, ['$result' => $answer]);
4263 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4264 return api_format_data("photo_update", $type, ['$result' => $answer]);
4266 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4269 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4274 * @brief delete a single photo from the database through api
4276 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4279 function api_fr_photo_delete($type)
4281 if (api_user() === false) {
4282 throw new ForbiddenException();
4285 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4287 // do several checks on input parameters
4288 // we do not allow calls without photo id
4289 if ($photo_id == null) {
4290 throw new BadRequestException("no photo_id specified");
4292 // check if photo is existing in database
4294 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4298 if (!DBM::is_result($r)) {
4299 throw new BadRequestException("photo not available");
4301 // now we can perform on the deletion of the photo
4302 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4304 // return success of deletion or error message
4306 // retrieve the id of the parent element (the photo element)
4308 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4309 intval(local_user()),
4313 if (!DBM::is_result($photo_item)) {
4314 throw new InternalServerErrorException("problem with deleting items occured");
4316 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4317 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4318 Item::deleteById($photo_item[0]['id']);
4320 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4321 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4323 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4329 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4331 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4332 * @return string|array
4334 function api_fr_photo_detail($type)
4336 if (api_user() === false) {
4337 throw new ForbiddenException();
4339 if (!x($_REQUEST, 'photo_id')) {
4340 throw new BadRequestException("No photo id.");
4343 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4344 $photo_id = $_REQUEST['photo_id'];
4346 // prepare json/xml output with data from database for the requested photo
4347 $data = prepare_photo_data($type, $scale, $photo_id);
4349 return api_format_data("photo_detail", $type, $data);
4354 * Updates the user’s profile image.
4356 * @brief updates the profile image for the user (either a specified profile or the default profile)
4358 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4361 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4363 function api_account_update_profile_image($type)
4365 if (api_user() === false) {
4366 throw new ForbiddenException();
4369 $profileid = defaults($_REQUEST, 'profile_id', 0);
4371 // error if image data is missing
4372 if (!x($_FILES, 'image')) {
4373 throw new BadRequestException("no media data submitted");
4376 // check if specified profile id is valid
4377 if ($profileid != 0) {
4379 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4383 // error message if specified profile id is not in database
4384 if (!DBM::is_result($r)) {
4385 throw new BadRequestException("profile_id not available");
4387 $is_default_profile = $r['profile'];
4389 $is_default_profile = 1;
4392 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4394 if (x($_FILES, 'image')) {
4395 $media = $_FILES['image'];
4396 } elseif (x($_FILES, 'media')) {
4397 $media = $_FILES['media'];
4399 // save new profile image
4400 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4403 if (is_array($media['type'])) {
4404 $filetype = $media['type'][0];
4406 $filetype = $media['type'];
4408 if ($filetype == "image/jpeg") {
4410 } elseif ($filetype == "image/png") {
4413 // change specified profile or all profiles to the new resource-id
4414 if ($is_default_profile) {
4416 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4417 dbesc($data['photo']['id']),
4418 intval(local_user())
4422 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4423 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4424 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4425 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4426 intval(local_user())
4430 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4431 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4432 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4433 intval($_REQUEST['profile']),
4434 intval(local_user())
4438 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4439 // so that browsers will do a cache update unconditionally
4442 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4443 dbesc(DateTimeFormat::utcNow()),
4444 intval(local_user())
4447 // Update global directory in background
4448 //$user = api_get_user(get_app());
4449 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4450 if ($url && strlen(Config::get('system', 'directory'))) {
4451 Worker::add(PRIORITY_LOW, "Directory", $url);
4454 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4456 // output for client
4458 return api_account_verify_credentials($type);
4460 // SaveMediaToDatabase failed for some reason
4461 throw new InternalServerErrorException("image upload failed");
4465 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4466 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4467 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4468 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4469 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4470 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4471 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4472 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4473 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4476 * Update user profile
4478 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4480 * @return array|string
4482 function api_account_update_profile($type)
4484 $local_user = api_user();
4485 $api_user = api_get_user(get_app());
4487 if (!empty($_POST['name'])) {
4488 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4489 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4490 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4491 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4494 if (isset($_POST['description'])) {
4495 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4496 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4497 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4500 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4501 // Update global directory in background
4502 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4503 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4506 return api_account_verify_credentials($type);
4509 /// @TODO move to top of file or somewhere better
4510 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4514 * @param string $acl_string
4516 function check_acl_input($acl_string)
4518 if ($acl_string == null || $acl_string == " ") {
4521 $contact_not_found = false;
4523 // split <x><y><z> into array of cid's
4524 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4526 // check for each cid if it is available on server
4527 $cid_array = $array[0];
4528 foreach ($cid_array as $cid) {
4529 $cid = str_replace("<", "", $cid);
4530 $cid = str_replace(">", "", $cid);
4532 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4536 $contact_not_found |= !DBM::is_result($contact);
4538 return $contact_not_found;
4543 * @param string $mediatype
4544 * @param array $media
4545 * @param string $type
4546 * @param string $album
4547 * @param string $allow_cid
4548 * @param string $deny_cid
4549 * @param string $allow_gid
4550 * @param string $deny_gid
4551 * @param string $desc
4552 * @param integer $profile
4553 * @param boolean $visibility
4554 * @param string $photo_id
4556 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)
4564 if (is_array($media)) {
4565 if (is_array($media['tmp_name'])) {
4566 $src = $media['tmp_name'][0];
4568 $src = $media['tmp_name'];
4570 if (is_array($media['name'])) {
4571 $filename = basename($media['name'][0]);
4573 $filename = basename($media['name']);
4575 if (is_array($media['size'])) {
4576 $filesize = intval($media['size'][0]);
4578 $filesize = intval($media['size']);
4580 if (is_array($media['type'])) {
4581 $filetype = $media['type'][0];
4583 $filetype = $media['type'];
4587 if ($filetype == "") {
4588 $filetype=Image::guessType($filename);
4590 $imagedata = getimagesize($src);
4592 $filetype = $imagedata['mime'];
4595 "File upload src: " . $src . " - filename: " . $filename .
4596 " - size: " . $filesize . " - type: " . $filetype,
4600 // check if there was a php upload error
4601 if ($filesize == 0 && $media['error'] == 1) {
4602 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4604 // check against max upload size within Friendica instance
4605 $maximagesize = Config::get('system', 'maximagesize');
4606 if ($maximagesize && ($filesize > $maximagesize)) {
4607 $formattedBytes = formatBytes($maximagesize);
4608 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4611 // create Photo instance with the data of the image
4612 $imagedata = @file_get_contents($src);
4613 $Image = new Image($imagedata, $filetype);
4614 if (! $Image->isValid()) {
4615 throw new InternalServerErrorException("unable to process image data");
4618 // check orientation of image
4619 $Image->orient($src);
4622 // check max length of images on server
4623 $max_length = Config::get('system', 'max_image_length');
4624 if (! $max_length) {
4625 $max_length = MAX_IMAGE_LENGTH;
4627 if ($max_length > 0) {
4628 $Image->scaleDown($max_length);
4629 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4631 $width = $Image->getWidth();
4632 $height = $Image->getHeight();
4634 // create a new resource-id if not already provided
4635 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4637 if ($mediatype == "photo") {
4638 // upload normal image (scales 0, 1, 2)
4639 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4641 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4643 logger("photo upload: image upload with scale 0 (original size) failed");
4645 if ($width > 640 || $height > 640) {
4646 $Image->scaleDown(640);
4647 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4649 logger("photo upload: image upload with scale 1 (640x640) failed");
4653 if ($width > 320 || $height > 320) {
4654 $Image->scaleDown(320);
4655 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4657 logger("photo upload: image upload with scale 2 (320x320) failed");
4660 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4661 } elseif ($mediatype == "profileimage") {
4662 // upload profile image (scales 4, 5, 6)
4663 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4665 if ($width > 175 || $height > 175) {
4666 $Image->scaleDown(175);
4667 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4669 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4673 if ($width > 80 || $height > 80) {
4674 $Image->scaleDown(80);
4675 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4677 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4681 if ($width > 48 || $height > 48) {
4682 $Image->scaleDown(48);
4683 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4685 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4688 $Image->__destruct();
4689 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4693 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4694 if ($photo_id == null && $mediatype == "photo") {
4695 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4697 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4698 return prepare_photo_data($type, false, $hash);
4700 throw new InternalServerErrorException("image upload failed");
4706 * @param string $hash
4707 * @param string $allow_cid
4708 * @param string $deny_cid
4709 * @param string $allow_gid
4710 * @param string $deny_gid
4711 * @param string $filetype
4712 * @param boolean $visibility
4714 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4716 // get data about the api authenticated user
4717 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4718 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4721 $arr['guid'] = get_guid(32);
4722 $arr['uid'] = intval(api_user());
4724 $arr['parent-uri'] = $uri;
4725 $arr['type'] = 'photo';
4727 $arr['resource-id'] = $hash;
4728 $arr['contact-id'] = $owner_record[0]['id'];
4729 $arr['owner-name'] = $owner_record[0]['name'];
4730 $arr['owner-link'] = $owner_record[0]['url'];
4731 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4732 $arr['author-name'] = $owner_record[0]['name'];
4733 $arr['author-link'] = $owner_record[0]['url'];
4734 $arr['author-avatar'] = $owner_record[0]['thumb'];
4736 $arr['allow_cid'] = $allow_cid;
4737 $arr['allow_gid'] = $allow_gid;
4738 $arr['deny_cid'] = $deny_cid;
4739 $arr['deny_gid'] = $deny_gid;
4740 $arr['visible'] = $visibility;
4744 'image/jpeg' => 'jpg',
4745 'image/png' => 'png',
4746 'image/gif' => 'gif'
4749 // adds link to the thumbnail scale photo
4750 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4751 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4754 // do the magic for storing the item in the database and trigger the federation to other contacts
4760 * @param string $type
4762 * @param string $photo_id
4766 function prepare_photo_data($type, $scale, $photo_id)
4768 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4769 $data_sql = ($scale === false ? "" : "data, ");
4771 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4772 // clients needs to convert this in their way for further processing
4774 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4775 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4776 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4777 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4779 intval(local_user()),
4785 'image/jpeg' => 'jpg',
4786 'image/png' => 'png',
4787 'image/gif' => 'gif'
4790 // prepare output data for photo
4791 if (DBM::is_result($r)) {
4792 $data = ['photo' => $r[0]];
4793 $data['photo']['id'] = $data['photo']['resource-id'];
4794 if ($scale !== false) {
4795 $data['photo']['data'] = base64_encode($data['photo']['data']);
4797 unset($data['photo']['datasize']); //needed only with scale param
4799 if ($type == "xml") {
4800 $data['photo']['links'] = [];
4801 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4802 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4804 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4807 $data['photo']['link'] = [];
4808 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4810 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4811 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4815 unset($data['photo']['resource-id']);
4816 unset($data['photo']['minscale']);
4817 unset($data['photo']['maxscale']);
4819 throw new NotFoundException();
4822 // retrieve item element for getting activities (like, dislike etc.) related to photo
4824 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4825 intval(local_user()),
4828 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4830 // retrieve comments on photo
4832 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4833 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4834 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4835 `contact`.`id` AS `cid`
4837 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4838 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4839 WHERE `item`.`parent` = %d AND `item`.`visible`
4840 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4841 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4842 intval($item[0]['parent']),
4844 dbesc(ACTIVITY_POST)
4847 // prepare output of comments
4848 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4850 if ($type == "xml") {
4852 foreach ($commentData as $comment) {
4853 $comments[$k++ . ":comment"] = $comment;
4856 foreach ($commentData as $comment) {
4857 $comments[] = $comment;
4860 $data['photo']['friendica_comments'] = $comments;
4862 // include info if rights on photo and rights on item are mismatching
4863 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4864 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4865 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4866 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4867 $data['photo']['rights_mismatch'] = $rights_mismatch;
4874 * Similar as /mod/redir.php
4875 * redirect to 'url' after dfrn auth
4877 * Why this when there is mod/redir.php already?
4878 * This use api_user() and api_login()
4881 * c_url: url of remote contact to auth to
4882 * url: string, url to redirect after auth
4884 function api_friendica_remoteauth()
4886 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4887 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4889 if ($url === '' || $c_url === '') {
4890 throw new BadRequestException("Wrong parameters.");
4893 $c_url = normalise_link($c_url);
4897 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4899 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4900 throw new BadRequestException("Unknown contact");
4903 $cid = $contact['id'];
4905 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4907 if ($contact['duplex'] && $contact['issued-id']) {
4908 $orig_id = $contact['issued-id'];
4909 $dfrn_id = '1:' . $orig_id;
4911 if ($contact['duplex'] && $contact['dfrn-id']) {
4912 $orig_id = $contact['dfrn-id'];
4913 $dfrn_id = '0:' . $orig_id;
4916 $sec = random_string();
4919 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4920 VALUES( %d, %s, '%s', '%s', %d )",
4928 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4929 $dest = ($url ? '&destination_url=' . $url : '');
4931 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4932 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4933 . '&type=profile&sec=' . $sec . $dest
4936 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4939 * @brief Return the item shared, if the item contains only the [share] tag
4941 * @param array $item Sharer item
4942 * @return array|false Shared item or false if not a reshare
4944 function api_share_as_retweet(&$item)
4946 $body = trim($item["body"]);
4948 if (Diaspora::isReshare($body, false)===false) {
4952 /// @TODO "$1" should maybe mean '$1' ?
4953 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4955 * Skip if there is no shared message in there
4956 * we already checked this in diaspora::isReshare()
4957 * but better one more than one less...
4959 if ($body == $attributes) {
4964 // build the fake reshared item
4965 $reshared_item = $item;
4968 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4969 if ($matches[1] != "") {
4970 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4973 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4974 if ($matches[1] != "") {
4975 $author = $matches[1];
4979 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4980 if ($matches[1] != "") {
4981 $profile = $matches[1];
4984 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4985 if ($matches[1] != "") {
4986 $profile = $matches[1];
4990 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4991 if ($matches[1] != "") {
4992 $avatar = $matches[1];
4995 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4996 if ($matches[1] != "") {
4997 $avatar = $matches[1];
5001 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5002 if ($matches[1] != "") {
5003 $link = $matches[1];
5006 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5007 if ($matches[1] != "") {
5008 $link = $matches[1];
5012 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5013 if ($matches[1] != "") {
5014 $posted = $matches[1];
5017 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5018 if ($matches[1] != "") {
5019 $posted = $matches[1];
5022 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5024 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5028 $reshared_item["body"] = $shared_body;
5029 $reshared_item["author-name"] = $author;
5030 $reshared_item["author-link"] = $profile;
5031 $reshared_item["author-avatar"] = $avatar;
5032 $reshared_item["plink"] = $link;
5033 $reshared_item["created"] = $posted;
5034 $reshared_item["edited"] = $posted;
5036 return $reshared_item;
5041 * @param string $profile
5043 * @return string|false
5044 * @todo remove trailing junk from profile url
5045 * @todo pump.io check has to check the website
5047 function api_get_nick($profile)
5052 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5053 dbesc(normalise_link($profile))
5056 if (DBM::is_result($r)) {
5057 $nick = $r[0]["nick"];
5062 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5063 dbesc(normalise_link($profile))
5066 if (DBM::is_result($r)) {
5067 $nick = $r[0]["nick"];
5072 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5073 if ($friendica != $profile) {
5079 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5080 if ($diaspora != $profile) {
5086 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5087 if ($twitter != $profile) {
5094 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5095 if ($StatusnetHost != $profile) {
5096 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5097 if ($StatusnetUser != $profile) {
5098 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5099 $user = json_decode($UserData);
5101 $nick = $user->screen_name;
5107 // To-Do: look at the page if its really a pumpio site
5108 //if (!$nick == "") {
5109 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5110 // if ($pumpio != $profile)
5112 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5125 * @param array $item
5129 function api_in_reply_to($item)
5133 $in_reply_to['status_id'] = null;
5134 $in_reply_to['user_id'] = null;
5135 $in_reply_to['status_id_str'] = null;
5136 $in_reply_to['user_id_str'] = null;
5137 $in_reply_to['screen_name'] = null;
5139 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5141 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5142 intval($item['uid']),
5143 dbesc($item['thr-parent'])
5146 if (DBM::is_result($r)) {
5147 $in_reply_to['status_id'] = intval($r[0]['id']);
5149 $in_reply_to['status_id'] = intval($item['parent']);
5152 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5155 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
5156 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5157 WHERE `item`.`id` = %d LIMIT 1",
5158 intval($in_reply_to['status_id'])
5161 if (DBM::is_result($r)) {
5162 if ($r[0]['nick'] == "") {
5163 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5166 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5167 $in_reply_to['user_id'] = intval($r[0]['id']);
5168 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5171 // There seems to be situation, where both fields are identical:
5172 // https://github.com/friendica/friendica/issues/1010
5173 // This is a bugfix for that.
5174 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5175 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5176 $in_reply_to['status_id'] = null;
5177 $in_reply_to['user_id'] = null;
5178 $in_reply_to['status_id_str'] = null;
5179 $in_reply_to['user_id_str'] = null;
5180 $in_reply_to['screen_name'] = null;
5184 return $in_reply_to;
5189 * @param string $Text
5193 function api_clean_plain_items($Text)
5195 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5197 $Text = BBCode::cleanPictureLinks($Text);
5198 $URLSearchString = "^\[\]";
5200 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
5202 if ($include_entities == "true") {
5203 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
5206 // Simplify "attachment" element
5207 $Text = api_clean_attachments($Text);
5213 * @brief Removes most sharing information for API text export
5215 * @param string $body The original body
5217 * @return string Cleaned body
5219 function api_clean_attachments($body)
5221 $data = BBCode::getAttachmentData($body);
5228 if (isset($data["text"])) {
5229 $body = $data["text"];
5231 if (($body == "") && isset($data["title"])) {
5232 $body = $data["title"];
5234 if (isset($data["url"])) {
5235 $body .= "\n".$data["url"];
5237 $body .= $data["after"];
5244 * @param array $contacts
5248 function api_best_nickname(&$contacts)
5252 if (count($contacts) == 0) {
5256 foreach ($contacts as $contact) {
5257 if ($contact["network"] == "") {
5258 $contact["network"] = "dfrn";
5259 $best_contact = [$contact];
5263 if (sizeof($best_contact) == 0) {
5264 foreach ($contacts as $contact) {
5265 if ($contact["network"] == "dfrn") {
5266 $best_contact = [$contact];
5271 if (sizeof($best_contact) == 0) {
5272 foreach ($contacts as $contact) {
5273 if ($contact["network"] == "dspr") {
5274 $best_contact = [$contact];
5279 if (sizeof($best_contact) == 0) {
5280 foreach ($contacts as $contact) {
5281 if ($contact["network"] == "stat") {
5282 $best_contact = [$contact];
5287 if (sizeof($best_contact) == 0) {
5288 foreach ($contacts as $contact) {
5289 if ($contact["network"] == "pump") {
5290 $best_contact = [$contact];
5295 if (sizeof($best_contact) == 0) {
5296 foreach ($contacts as $contact) {
5297 if ($contact["network"] == "twit") {
5298 $best_contact = [$contact];
5303 if (sizeof($best_contact) == 1) {
5304 $contacts = $best_contact;
5306 $contacts = [$contacts[0]];
5311 * Return all or a specified group of the user with the containing contacts.
5313 * @param string $type Return type (atom, rss, xml, json)
5315 * @return array|string
5317 function api_friendica_group_show($type)
5321 if (api_user() === false) {
5322 throw new ForbiddenException();
5326 $user_info = api_get_user($a);
5327 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5328 $uid = $user_info['uid'];
5330 // get data of the specified group id or all groups if not specified
5333 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5337 // error message if specified gid is not in database
5338 if (!DBM::is_result($r)) {
5339 throw new BadRequestException("gid not available");
5343 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5348 // loop through all groups and retrieve all members for adding data in the user array
5349 foreach ($r as $rr) {
5350 $members = Contact::getByGroupId($rr['id']);
5353 if ($type == "xml") {
5354 $user_element = "users";
5356 foreach ($members as $member) {
5357 $user = api_get_user($a, $member['nurl']);
5358 $users[$k++.":user"] = $user;
5361 $user_element = "user";
5362 foreach ($members as $member) {
5363 $user = api_get_user($a, $member['nurl']);
5367 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5369 return api_format_data("groups", $type, ['group' => $grps]);
5371 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5375 * Delete the specified group of the user.
5377 * @param string $type Return type (atom, rss, xml, json)
5379 * @return array|string
5381 function api_friendica_group_delete($type)
5385 if (api_user() === false) {
5386 throw new ForbiddenException();
5390 $user_info = api_get_user($a);
5391 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5392 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5393 $uid = $user_info['uid'];
5395 // error if no gid specified
5396 if ($gid == 0 || $name == "") {
5397 throw new BadRequestException('gid or name not specified');
5400 // get data of the specified group id
5402 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5406 // error message if specified gid is not in database
5407 if (!DBM::is_result($r)) {
5408 throw new BadRequestException('gid not available');
5411 // get data of the specified group id and group name
5413 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5418 // error message if specified gid is not in database
5419 if (!DBM::is_result($rname)) {
5420 throw new BadRequestException('wrong group name');
5424 $ret = Group::removeByName($uid, $name);
5427 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5428 return api_format_data("group_delete", $type, ['result' => $success]);
5430 throw new BadRequestException('other API error');
5433 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5437 * Create the specified group with the posted array of contacts.
5439 * @param string $type Return type (atom, rss, xml, json)
5441 * @return array|string
5443 function api_friendica_group_create($type)
5447 if (api_user() === false) {
5448 throw new ForbiddenException();
5452 $user_info = api_get_user($a);
5453 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5454 $uid = $user_info['uid'];
5455 $json = json_decode($_POST['json'], true);
5456 $users = $json['user'];
5458 // error if no name specified
5460 throw new BadRequestException('group name not specified');
5463 // get data of the specified group name
5465 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5469 // error message if specified group name already exists
5470 if (DBM::is_result($rname)) {
5471 throw new BadRequestException('group name already exists');
5474 // check if specified group name is a deleted group
5476 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5480 // error message if specified group name already exists
5481 if (DBM::is_result($rname)) {
5482 $reactivate_group = true;
5486 $ret = Group::create($uid, $name);
5488 $gid = Group::getIdByName($uid, $name);
5490 throw new BadRequestException('other API error');
5494 $erroraddinguser = false;
5496 foreach ($users as $user) {
5497 $cid = $user['cid'];
5498 // check if user really exists as contact
5500 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5504 if (count($contact)) {
5505 Group::addMember($gid, $cid);
5507 $erroraddinguser = true;
5508 $errorusers[] = $cid;
5512 // return success message incl. missing users in array
5513 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5514 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5515 return api_format_data("group_create", $type, ['result' => $success]);
5517 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5521 * Update the specified group with the posted array of contacts.
5523 * @param string $type Return type (atom, rss, xml, json)
5525 * @return array|string
5527 function api_friendica_group_update($type)
5531 if (api_user() === false) {
5532 throw new ForbiddenException();
5536 $user_info = api_get_user($a);
5537 $uid = $user_info['uid'];
5538 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5539 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5540 $json = json_decode($_POST['json'], true);
5541 $users = $json['user'];
5543 // error if no name specified
5545 throw new BadRequestException('group name not specified');
5548 // error if no gid specified
5550 throw new BadRequestException('gid not specified');
5554 $members = Contact::getByGroupId($gid);
5555 foreach ($members as $member) {
5556 $cid = $member['id'];
5557 foreach ($users as $user) {
5558 $found = ($user['cid'] == $cid ? true : false);
5561 Group::removeMemberByName($uid, $name, $cid);
5566 $erroraddinguser = false;
5568 foreach ($users as $user) {
5569 $cid = $user['cid'];
5570 // check if user really exists as contact
5572 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5577 if (count($contact)) {
5578 Group::addMember($gid, $cid);
5580 $erroraddinguser = true;
5581 $errorusers[] = $cid;
5585 // return success message incl. missing users in array
5586 $status = ($erroraddinguser ? "missing user" : "ok");
5587 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5588 return api_format_data("group_update", $type, ['result' => $success]);
5591 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5595 * @param string $type Return type (atom, rss, xml, json)
5597 * @return array|string
5599 function api_friendica_activity($type)
5603 if (api_user() === false) {
5604 throw new ForbiddenException();
5606 $verb = strtolower($a->argv[3]);
5607 $verb = preg_replace("|\..*$|", "", $verb);
5609 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5611 $res = Item::performLike($id, $verb);
5614 if ($type == "xml") {
5619 return api_format_data('ok', $type, ['ok' => $ok]);
5621 throw new BadRequestException('Error adding activity');
5625 /// @TODO move to top of file or somewhere better
5626 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5627 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5628 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5629 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5630 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5631 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5632 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5633 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5634 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5635 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5638 * @brief Returns notifications
5640 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5643 function api_friendica_notification($type)
5647 if (api_user() === false) {
5648 throw new ForbiddenException();
5651 throw new BadRequestException("Invalid argument count");
5653 $nm = new NotificationsManager();
5655 $notes = $nm->getAll([], "+seen -date", 50);
5657 if ($type == "xml") {
5659 foreach ($notes as $note) {
5660 $xmlnotes[] = ["@attributes" => $note];
5666 return api_format_data("notes", $type, ['note' => $notes]);
5670 * POST request with 'id' param as notification id
5672 * @brief Set notification as seen and returns associated item (if possible)
5674 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5677 function api_friendica_notification_seen($type)
5681 if (api_user() === false) {
5682 throw new ForbiddenException();
5685 throw new BadRequestException("Invalid argument count");
5688 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5690 $nm = new NotificationsManager();
5691 $note = $nm->getByID($id);
5692 if (is_null($note)) {
5693 throw new BadRequestException("Invalid argument");
5696 $nm->setSeen($note);
5697 if ($note['otype']=='item') {
5698 // would be really better with an ItemsManager and $im->getByID() :-P
5700 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5701 intval($note['iid']),
5702 intval(local_user())
5705 // we found the item, return it to the user
5706 $user_info = api_get_user($a);
5707 $ret = api_format_items($r, $user_info, false, $type);
5708 $data = ['status' => $ret];
5709 return api_format_data("status", $type, $data);
5711 // the item can't be found, but we set the note as seen, so we count this as a success
5713 return api_format_data('result', $type, ['result' => "success"]);
5716 /// @TODO move to top of file or somewhere better
5717 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5718 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5721 * @brief update a direct_message to seen state
5723 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5724 * @return string (success result=ok, error result=error with error message)
5726 function api_friendica_direct_messages_setseen($type)
5729 if (api_user() === false) {
5730 throw new ForbiddenException();
5734 $user_info = api_get_user($a);
5735 $uid = $user_info['uid'];
5736 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5738 // return error if id is zero
5740 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5741 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5744 // get data of the specified message id
5746 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5751 // error message if specified id is not in database
5752 if (!DBM::is_result($r)) {
5753 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5754 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5757 // update seen indicator
5759 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5766 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5767 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5769 $answer = ['result' => 'error', 'message' => 'unknown error'];
5770 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5774 /// @TODO move to top of file or somewhere better
5775 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5778 * @brief search for direct_messages containing a searchstring through api
5780 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5781 * @param string $box
5782 * @return string (success: success=true if found and search_result contains found messages,
5783 * success=false if nothing was found, search_result='nothing found',
5784 * error: result=error with error message)
5786 function api_friendica_direct_messages_search($type, $box = "")
5790 if (api_user() === false) {
5791 throw new ForbiddenException();
5795 $user_info = api_get_user($a);
5796 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5797 $uid = $user_info['uid'];
5799 // error if no searchstring specified
5800 if ($searchstring == "") {
5801 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5802 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5805 // get data for the specified searchstring
5807 "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",
5809 dbesc('%'.$searchstring.'%')
5812 $profile_url = $user_info["url"];
5814 // message if nothing was found
5815 if (!DBM::is_result($r)) {
5816 $success = ['success' => false, 'search_results' => 'problem with query'];
5817 } elseif (count($r) == 0) {
5818 $success = ['success' => false, 'search_results' => 'nothing found'];
5821 foreach ($r as $item) {
5822 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5823 $recipient = $user_info;
5824 $sender = api_get_user($a, normalise_link($item['contact-url']));
5825 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5826 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5827 $sender = $user_info;
5830 $ret[] = api_format_messages($item, $recipient, $sender);
5832 $success = ['success' => true, 'search_results' => $ret];
5835 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5838 /// @TODO move to top of file or somewhere better
5839 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5842 * @brief return data of all the profiles a user has to the client
5844 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5847 function api_friendica_profile_show($type)
5851 if (api_user() === false) {
5852 throw new ForbiddenException();
5856 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5858 // retrieve general information about profiles for user
5859 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5860 $directory = Config::get('system', 'directory');
5862 // get data of the specified profile id or all profiles of the user if not specified
5863 if ($profileid != 0) {
5865 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5870 // error message if specified gid is not in database
5871 if (!DBM::is_result($r)) {
5872 throw new BadRequestException("profile_id not available");
5876 "SELECT * FROM `profile` WHERE `uid` = %d",
5880 // loop through all returned profiles and retrieve data and users
5882 foreach ($r as $rr) {
5883 $profile = api_format_items_profiles($rr);
5885 // select all users from contact table, loop and prepare standard return for user data
5888 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5890 intval($rr['profile_id'])
5893 foreach ($r as $rr) {
5894 $user = api_get_user($a, $rr['nurl']);
5895 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5897 $profile['users'] = $users;
5899 // add prepared profile data to array for final return
5900 if ($type == "xml") {
5901 $profiles[$k++ . ":profile"] = $profile;
5903 $profiles[] = $profile;
5907 // return settings, authenticated user and profiles data
5908 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5910 $result = ['multi_profiles' => $multi_profiles ? true : false,
5911 'global_dir' => $directory,
5912 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5913 'profiles' => $profiles];
5914 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5916 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5919 * Returns a list of saved searches.
5921 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5923 * @param string $type Return format: json or xml
5925 * @return string|array
5927 function api_saved_searches_list($type)
5929 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5932 while ($term = $terms->fetch()) {
5934 'name' => $term['term'],
5935 'query' => $term['term'],
5936 'id_str' => $term['id'],
5937 'id' => intval($term['id'])
5943 return api_format_data("terms", $type, ['terms' => $result]);
5946 /// @TODO move to top of file or somewhere better
5947 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5950 @TODO Maybe open to implement?
5952 [pagename] => api/1.1/statuses/lookup.json
5953 [id] => 605138389168451584
5954 [include_cards] => true
5955 [cards_platform] => Android-12
5956 [include_entities] => true
5957 [include_my_retweet] => 1
5959 [include_reply_count] => true
5960 [include_descendent_reply_count] => true
5964 Not implemented by now:
5965 statuses/retweets_of_me
5970 account/update_location
5971 account/update_profile_background_image
5974 friendica/profile/update
5975 friendica/profile/create
5976 friendica/profile/delete
5978 Not implemented in status.net:
5979 statuses/retweeted_to_me
5980 statuses/retweeted_by_me
5981 direct_messages/destroy
5983 account/update_delivery_device
5984 notifications/follow