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 'profile_image_url_profile_size' => $r[0]["thumb"],
651 'profile_image_url_large' => $r[0]["photo"],
652 'url' => $r[0]["url"],
653 'protected' => false,
654 'followers_count' => 0,
655 'friends_count' => 0,
657 'created_at' => api_date($r[0]["created"]),
658 'favourites_count' => 0,
660 'time_zone' => 'UTC',
661 'geo_enabled' => false,
663 'statuses_count' => 0,
665 'contributors_enabled' => false,
666 'is_translator' => false,
667 'is_translation_enabled' => false,
668 'following' => false,
669 'follow_request_sent' => false,
670 'statusnet_blocking' => false,
671 'notifications' => false,
672 'statusnet_profile_url' => $r[0]["url"],
674 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
676 'network' => $r[0]["network"],
681 throw new BadRequestException("User not found.");
685 if ($uinfo[0]['self']) {
686 if ($uinfo[0]['network'] == "") {
687 $uinfo[0]['network'] = NETWORK_DFRN;
691 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
695 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
699 /// @TODO old-lost code? (twice)
700 // Counting is deactivated by now, due to performance issues
701 // count public wall messages
702 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
703 // intval($uinfo[0]['uid'])
705 //$countitms = $r[0]['count'];
708 // Counting is deactivated by now, due to performance issues
709 //$r = q("SELECT count(*) as `count` FROM `item`
710 // WHERE `contact-id` = %d",
711 // intval($uinfo[0]['id'])
713 //$countitms = $r[0]['count'];
717 /// @TODO old-lost code? (twice)
719 // Counting is deactivated by now, due to performance issues
721 $r = q("SELECT count(*) as `count` FROM `contact`
722 WHERE `uid` = %d AND `rel` IN ( %d, %d )
723 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
724 intval($uinfo[0]['uid']),
725 intval(CONTACT_IS_SHARING),
726 intval(CONTACT_IS_FRIEND)
728 $countfriends = $r[0]['count'];
730 $r = q("SELECT count(*) as `count` FROM `contact`
731 WHERE `uid` = %d AND `rel` IN ( %d, %d )
732 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
733 intval($uinfo[0]['uid']),
734 intval(CONTACT_IS_FOLLOWER),
735 intval(CONTACT_IS_FRIEND)
737 $countfollowers = $r[0]['count'];
739 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
740 intval($uinfo[0]['uid'])
742 $starred = $r[0]['count'];
745 if (! $uinfo[0]['self']) {
755 // Add a nick if it isn't present there
756 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
757 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
760 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
762 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
764 if (!empty($profile[0]['about'])) {
765 $description = $profile[0]['about'];
767 $description = $uinfo[0]["about"];
770 if (!empty($usr[0]['default-location'])) {
771 $location = $usr[0]['default-location'];
772 } elseif (!empty($uinfo[0]["location"])) {
773 $location = $uinfo[0]["location"];
775 $location = $network_name;
779 'id' => intval($pcontact_id),
780 'id_str' => (string) intval($pcontact_id),
781 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
782 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
783 'location' => $location,
784 'description' => $description,
785 'profile_image_url' => $uinfo[0]['micro'],
786 'profile_image_url_https' => $uinfo[0]['micro'],
787 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
788 'profile_image_url_large' => $uinfo[0]["photo"],
789 'url' => $uinfo[0]['url'],
790 'protected' => false,
791 'followers_count' => intval($countfollowers),
792 'friends_count' => intval($countfriends),
794 'created_at' => api_date($uinfo[0]['created']),
795 'favourites_count' => intval($starred),
797 'time_zone' => 'UTC',
798 'geo_enabled' => false,
800 'statuses_count' => intval($countitms),
802 'contributors_enabled' => false,
803 'is_translator' => false,
804 'is_translation_enabled' => false,
805 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
806 'follow_request_sent' => false,
807 'statusnet_blocking' => false,
808 'notifications' => false,
810 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
811 'statusnet_profile_url' => $uinfo[0]['url'],
812 'uid' => intval($uinfo[0]['uid']),
813 'cid' => intval($uinfo[0]['cid']),
814 'self' => $uinfo[0]['self'],
815 'network' => $uinfo[0]['network'],
818 // If this is a local user and it uses Frio, we can get its color preferences.
820 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
821 if ($theme_info['theme'] === 'frio') {
822 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
823 if ($schema && ($schema != '---')) {
824 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
825 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
826 require_once $schemefile;
829 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
830 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
831 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
837 $link_color = "#6fdbe8";
840 $bgcolor = "#ededed";
843 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
844 $ret['profile_link_color'] = str_replace('#', '', $link_color);
845 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
853 * @brief return api-formatted array for item's author and owner
855 * @param object $a App
856 * @param array $item item from db
857 * @return array(array:author, array:owner)
859 function api_item_get_user(App $a, $item)
861 $status_user = api_get_user($a, $item["author-link"]);
863 $status_user["protected"] = (($item["allow_cid"] != "") ||
864 ($item["allow_gid"] != "") ||
865 ($item["deny_cid"] != "") ||
866 ($item["deny_gid"] != "") ||
869 if ($item['thr-parent'] == $item['uri']) {
870 $owner_user = api_get_user($a, $item["owner-link"]);
872 $owner_user = $status_user;
875 return ([$status_user, $owner_user]);
879 * @brief walks recursively through an array with the possibility to change value and key
881 * @param array $array The array to walk through
882 * @param string $callback The callback function
884 * @return array the transformed array
886 function api_walk_recursive(array &$array, callable $callback)
890 foreach ($array as $k => $v) {
892 if ($callback($v, $k)) {
893 $new_array[$k] = api_walk_recursive($v, $callback);
896 if ($callback($v, $k)) {
907 * @brief Callback function to transform the array in an array that can be transformed in a XML file
909 * @param mixed $item Array item value
910 * @param string $key Array key
912 * @return boolean Should the array item be deleted?
914 function api_reformat_xml(&$item, &$key)
916 if (is_bool($item)) {
917 $item = ($item ? "true" : "false");
920 if (substr($key, 0, 10) == "statusnet_") {
921 $key = "statusnet:".substr($key, 10);
922 } elseif (substr($key, 0, 10) == "friendica_") {
923 $key = "friendica:".substr($key, 10);
925 /// @TODO old-lost code?
927 // $key = "default:".$key;
933 * @brief Creates the XML from a JSON style array
935 * @param array $data JSON style array
936 * @param string $root_element Name of the root element
938 * @return string The XML data
940 function api_create_xml($data, $root_element)
942 $childname = key($data);
943 $data2 = array_pop($data);
946 $namespaces = ["" => "http://api.twitter.com",
947 "statusnet" => "http://status.net/schema/api/1/",
948 "friendica" => "http://friendi.ca/schema/api/1/",
949 "georss" => "http://www.georss.org/georss"];
951 /// @todo Auto detection of needed namespaces
952 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
956 if (is_array($data2)) {
957 api_walk_recursive($data2, "api_reformat_xml");
964 foreach ($data2 as $item) {
965 $data4[$i++.":".$childname] = $item;
971 $data3 = [$root_element => $data2];
973 $ret = XML::fromArray($data3, $xml, false, $namespaces);
978 * @brief Formats the data according to the data type
980 * @param string $root_element Name of the root element
981 * @param string $type Return type (atom, rss, xml, json)
982 * @param array $data JSON style array
984 * @return (string|object|array) XML data or JSON data
986 function api_format_data($root_element, $type, $data)
992 $ret = api_create_xml($data, $root_element);
1007 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
1008 * returns a 401 status code and an error message if not.
1009 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
1011 * @param string $type Return type (atom, rss, xml, json)
1013 function api_account_verify_credentials($type)
1018 if (api_user() === false) {
1019 throw new ForbiddenException();
1022 unset($_REQUEST["user_id"]);
1023 unset($_GET["user_id"]);
1025 unset($_REQUEST["screen_name"]);
1026 unset($_GET["screen_name"]);
1028 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1030 $user_info = api_get_user($a);
1032 // "verified" isn't used here in the standard
1033 unset($user_info["verified"]);
1035 // - Adding last status
1036 if (!$skip_status) {
1037 $user_info["status"] = api_status_show("raw");
1038 if (!count($user_info["status"])) {
1039 unset($user_info["status"]);
1041 unset($user_info["status"]["user"]);
1045 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1046 unset($user_info["uid"]);
1047 unset($user_info["self"]);
1049 return api_format_data("user", $type, ['user' => $user_info]);
1052 /// @TODO move to top of file or somewhere better
1053 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1056 * Get data from $_POST or $_GET
1060 function requestdata($k)
1062 if (x($_POST, $k)) {
1072 * Waitman Gobble Mod
1074 * @param string $type Return type (atom, rss, xml, json)
1076 * @return array|string
1078 function api_statuses_mediap($type)
1082 if (api_user() === false) {
1083 logger('api_statuses_update: no user');
1084 throw new ForbiddenException();
1086 $user_info = api_get_user($a);
1088 $_REQUEST['type'] = 'wall';
1089 $_REQUEST['profile_uid'] = api_user();
1090 $_REQUEST['api_source'] = true;
1091 $txt = requestdata('status');
1092 /// @TODO old-lost code?
1093 //$txt = urldecode(requestdata('status'));
1095 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1096 $txt = html2bb_video($txt);
1097 $config = HTMLPurifier_Config::createDefault();
1098 $config->set('Cache.DefinitionImpl', null);
1099 $purifier = new HTMLPurifier($config);
1100 $txt = $purifier->purify($txt);
1102 $txt = HTML::toBBCode($txt);
1104 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1106 // tell wall_upload function to return img info instead of echo
1107 $_REQUEST['hush'] = 'yeah';
1108 $bebop = wall_upload_post($a);
1110 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1111 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1114 // this should output the last post (the one we just posted).
1115 return api_status_show($type);
1118 /// @TODO move this to top of file or somewhere better!
1119 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1122 * Updates the user’s current status.
1124 * @param string $type Return type (atom, rss, xml, json)
1126 * @return array|string
1127 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1129 function api_statuses_update($type)
1134 if (api_user() === false) {
1135 logger('api_statuses_update: no user');
1136 throw new ForbiddenException();
1141 // convert $_POST array items to the form we use for web posts.
1142 if (requestdata('htmlstatus')) {
1143 $txt = requestdata('htmlstatus');
1144 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1145 $txt = html2bb_video($txt);
1147 $config = HTMLPurifier_Config::createDefault();
1148 $config->set('Cache.DefinitionImpl', null);
1150 $purifier = new HTMLPurifier($config);
1151 $txt = $purifier->purify($txt);
1153 $_REQUEST['body'] = HTML::toBBCode($txt);
1156 $_REQUEST['body'] = requestdata('status');
1159 $_REQUEST['title'] = requestdata('title');
1161 $parent = requestdata('in_reply_to_status_id');
1163 // Twidere sends "-1" if it is no reply ...
1164 if ($parent == -1) {
1168 if (ctype_digit($parent)) {
1169 $_REQUEST['parent'] = $parent;
1171 $_REQUEST['parent_uri'] = $parent;
1174 if (requestdata('lat') && requestdata('long')) {
1175 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1177 $_REQUEST['profile_uid'] = api_user();
1180 $_REQUEST['type'] = 'net-comment';
1182 // Check for throttling (maximum posts per day, week and month)
1183 $throttle_day = Config::get('system', 'throttle_limit_day');
1184 if ($throttle_day > 0) {
1185 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1188 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1189 AND `created` > '%s' AND `id` = `parent`",
1194 if (DBM::is_result($r)) {
1195 $posts_day = $r[0]["posts_day"];
1200 if ($posts_day > $throttle_day) {
1201 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1202 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1203 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));
1207 $throttle_week = Config::get('system', 'throttle_limit_week');
1208 if ($throttle_week > 0) {
1209 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1212 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1213 AND `created` > '%s' AND `id` = `parent`",
1218 if (DBM::is_result($r)) {
1219 $posts_week = $r[0]["posts_week"];
1224 if ($posts_week > $throttle_week) {
1225 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1226 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1227 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));
1231 $throttle_month = Config::get('system', 'throttle_limit_month');
1232 if ($throttle_month > 0) {
1233 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1236 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1237 AND `created` > '%s' AND `id` = `parent`",
1242 if (DBM::is_result($r)) {
1243 $posts_month = $r[0]["posts_month"];
1248 if ($posts_month > $throttle_month) {
1249 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1250 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1251 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));
1255 $_REQUEST['type'] = 'wall';
1258 if (x($_FILES, 'media')) {
1259 // upload the image if we have one
1260 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1261 $media = wall_upload_post($a);
1262 if (strlen($media) > 0) {
1263 $_REQUEST['body'] .= "\n\n" . $media;
1267 // To-Do: Multiple IDs
1268 if (requestdata('media_ids')) {
1270 "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",
1271 intval(requestdata('media_ids')),
1274 if (DBM::is_result($r)) {
1275 $phototypes = Image::supportedTypes();
1276 $ext = $phototypes[$r[0]['type']];
1277 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1278 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1282 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1284 $_REQUEST['api_source'] = true;
1286 if (!x($_REQUEST, "source")) {
1287 $_REQUEST["source"] = api_source();
1290 // call out normal post function
1293 // this should output the last post (the one we just posted).
1294 return api_status_show($type);
1297 /// @TODO move to top of file or somewhere better
1298 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1299 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1302 * Uploads an image to Friendica.
1305 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1307 function api_media_upload()
1311 if (api_user() === false) {
1313 throw new ForbiddenException();
1318 if (!x($_FILES, 'media')) {
1320 throw new BadRequestException("No media.");
1323 $media = wall_upload_post($a, false);
1326 throw new InternalServerErrorException();
1330 $returndata["media_id"] = $media["id"];
1331 $returndata["media_id_string"] = (string)$media["id"];
1332 $returndata["size"] = $media["size"];
1333 $returndata["image"] = ["w" => $media["width"],
1334 "h" => $media["height"],
1335 "image_type" => $media["type"]];
1337 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1339 return ["media" => $returndata];
1342 /// @TODO move to top of file or somewhere better
1343 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1347 * @param string $type Return type (atom, rss, xml, json)
1349 * @return array|string
1351 function api_status_show($type)
1355 $user_info = api_get_user($a);
1357 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1359 if ($type == "raw") {
1360 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1365 // get last public wall message
1369 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1370 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1371 AND `item`.`type` != 'activity' $privacy_sql
1372 ORDER BY `item`.`id` DESC
1374 intval($user_info['cid']),
1376 dbesc($user_info['url']),
1377 dbesc(normalise_link($user_info['url'])),
1378 dbesc($user_info['url']),
1379 dbesc(normalise_link($user_info['url']))
1382 if (DBM::is_result($lastwall)) {
1383 $lastwall = $lastwall[0];
1385 $in_reply_to = api_in_reply_to($lastwall);
1387 $converted = api_convert_item($lastwall);
1389 if ($type == "xml") {
1390 $geo = "georss:point";
1396 'created_at' => api_date($lastwall['created']),
1397 'id' => intval($lastwall['id']),
1398 'id_str' => (string) $lastwall['id'],
1399 'text' => $converted["text"],
1400 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1401 'truncated' => false,
1402 'in_reply_to_status_id' => $in_reply_to['status_id'],
1403 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1404 'in_reply_to_user_id' => $in_reply_to['user_id'],
1405 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1406 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1407 'user' => $user_info,
1409 'coordinates' => "",
1411 'contributors' => "",
1412 'is_quote_status' => false,
1413 'retweet_count' => 0,
1414 'favorite_count' => 0,
1415 'favorited' => $lastwall['starred'] ? true : false,
1416 'retweeted' => false,
1417 'possibly_sensitive' => false,
1419 'statusnet_html' => $converted["html"],
1420 'statusnet_conversation_id' => $lastwall['parent'],
1421 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1424 if (count($converted["attachments"]) > 0) {
1425 $status_info["attachments"] = $converted["attachments"];
1428 if (count($converted["entities"]) > 0) {
1429 $status_info["entities"] = $converted["entities"];
1432 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1433 $status_info["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1434 } elseif (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1435 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['item_network'], $user_info['url']).')');
1438 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1439 unset($status_info["user"]["uid"]);
1440 unset($status_info["user"]["self"]);
1443 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1445 if ($type == "raw") {
1446 return $status_info;
1449 return api_format_data("statuses", $type, ['status' => $status_info]);
1453 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1454 * The author's most recent status will be returned inline.
1456 * @param string $type Return type (atom, rss, xml, json)
1457 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1459 function api_users_show($type)
1463 $user_info = api_get_user($a);
1467 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1468 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1469 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1470 AND `type`!='activity'
1471 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1475 dbesc(ACTIVITY_POST),
1476 intval($user_info['cid']),
1477 dbesc($user_info['url']),
1478 dbesc(normalise_link($user_info['url'])),
1479 dbesc($user_info['url']),
1480 dbesc(normalise_link($user_info['url']))
1483 if (DBM::is_result($lastwall)) {
1484 $lastwall = $lastwall[0];
1486 $in_reply_to = api_in_reply_to($lastwall);
1488 $converted = api_convert_item($lastwall);
1490 if ($type == "xml") {
1491 $geo = "georss:point";
1496 $user_info['status'] = [
1497 'text' => $converted["text"],
1498 'truncated' => false,
1499 'created_at' => api_date($lastwall['created']),
1500 'in_reply_to_status_id' => $in_reply_to['status_id'],
1501 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1502 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1503 'id' => intval($lastwall['contact-id']),
1504 'id_str' => (string) $lastwall['contact-id'],
1505 'in_reply_to_user_id' => $in_reply_to['user_id'],
1506 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1507 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1509 'favorited' => $lastwall['starred'] ? true : false,
1510 'statusnet_html' => $converted["html"],
1511 'statusnet_conversation_id' => $lastwall['parent'],
1512 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1515 if (count($converted["attachments"]) > 0) {
1516 $user_info["status"]["attachments"] = $converted["attachments"];
1519 if (count($converted["entities"]) > 0) {
1520 $user_info["status"]["entities"] = $converted["entities"];
1523 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1524 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1527 if (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1528 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) . ')');
1532 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1533 unset($user_info["uid"]);
1534 unset($user_info["self"]);
1536 return api_format_data("user", $type, ['user' => $user_info]);
1539 /// @TODO move to top of file or somewhere better
1540 api_register_func('api/users/show', 'api_users_show');
1541 api_register_func('api/externalprofile/show', 'api_users_show');
1544 * Search a public user account.
1546 * @param string $type Return type (atom, rss, xml, json)
1548 * @return array|string
1549 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1551 function api_users_search($type)
1557 if (x($_GET, 'q')) {
1558 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1560 if (!DBM::is_result($r)) {
1561 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1564 if (DBM::is_result($r)) {
1566 foreach ($r as $user) {
1567 $user_info = api_get_user($a, $user["id"]);
1569 if ($type == "xml") {
1570 $userlist[$k++.":user"] = $user_info;
1572 $userlist[] = $user_info;
1575 $userlist = ["users" => $userlist];
1577 throw new BadRequestException("User not found.");
1580 throw new BadRequestException("User not found.");
1583 return api_format_data("users", $type, $userlist);
1586 /// @TODO move to top of file or somewhere better
1587 api_register_func('api/users/search', 'api_users_search');
1590 * Return user objects
1592 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1594 * @param string $type Return format: json or xml
1596 * @return array|string
1597 * @throws NotFoundException if the results are empty.
1599 function api_users_lookup($type)
1603 if (x($_REQUEST['user_id'])) {
1604 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1606 $users[] = api_get_user(get_app(), $id);
1611 if (empty($users)) {
1612 throw new NotFoundException;
1615 return api_format_data("users", $type, ['users' => $users]);
1618 /// @TODO move to top of file or somewhere better
1619 api_register_func('api/users/lookup', 'api_users_lookup', true);
1622 * Returns statuses that match a specified query.
1624 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1626 * @param string $type Return format: json, xml, atom, rss
1628 * @return array|string
1629 * @throws BadRequestException if the "q" parameter is missing.
1631 function api_search($type)
1636 if (!x($_REQUEST, 'q')) {
1637 throw new BadRequestException("q parameter is required.");
1640 if (x($_REQUEST, 'rpp')) {
1641 $count = $_REQUEST['rpp'];
1642 } elseif (x($_REQUEST, 'count')) {
1643 $count = $_REQUEST['count'];
1648 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1649 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1650 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1652 $start = $page * $count;
1655 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1659 "SELECT ".item_fieldlists()."
1660 FROM `item` ".item_joins()."
1661 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1662 AND `item`.`body` LIKE CONCAT('%',?,'%')
1665 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1671 $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1673 return api_format_data("statuses", $type, $data);
1676 /// @TODO move to top of file or somewhere better
1677 api_register_func('api/search/tweets', 'api_search', true);
1678 api_register_func('api/search', 'api_search', true);
1681 * Returns the most recent statuses posted by the user and the users they follow.
1683 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1685 * @param string $type Return type (atom, rss, xml, json)
1687 * @todo Optional parameters
1688 * @todo Add reply info
1690 function api_statuses_home_timeline($type)
1694 if (api_user() === false) {
1695 throw new ForbiddenException();
1698 unset($_REQUEST["user_id"]);
1699 unset($_GET["user_id"]);
1701 unset($_REQUEST["screen_name"]);
1702 unset($_GET["screen_name"]);
1704 $user_info = api_get_user($a);
1705 // get last newtork messages
1708 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1709 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1713 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1714 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1715 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1716 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1717 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1719 $start = $page * $count;
1723 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1725 if ($exclude_replies > 0) {
1726 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1728 if ($conversation_id > 0) {
1729 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1733 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1734 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1735 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1736 `contact`.`id` AS `cid`
1738 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1739 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1740 WHERE `item`.`uid` = %d AND `verb` = '%s'
1741 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1744 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1746 dbesc(ACTIVITY_POST),
1752 $ret = api_format_items($r, $user_info, false, $type);
1754 // Set all posts from the query above to seen
1756 foreach ($r as $item) {
1757 $idarray[] = intval($item["id"]);
1760 $idlist = implode(",", $idarray);
1762 if ($idlist != "") {
1763 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1766 q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1770 $data = ['status' => $ret];
1774 $data = api_rss_extra($a, $data, $user_info);
1778 return api_format_data("statuses", $type, $data);
1781 /// @TODO move to top of file or somewhere better
1782 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1783 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1786 * Returns the most recent statuses from public users.
1788 * @param string $type Return type (atom, rss, xml, json)
1790 * @return array|string
1792 function api_statuses_public_timeline($type)
1796 if (api_user() === false) {
1797 throw new ForbiddenException();
1800 $user_info = api_get_user($a);
1801 // get last newtork messages
1804 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1805 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1809 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1810 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1811 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1812 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1813 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1815 $start = $page * $count;
1818 if ($exclude_replies && !$conversation_id) {
1820 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1824 "SELECT " . item_fieldlists() . "
1826 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1827 " . item_joins() . "
1828 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1829 AND NOT `user`.`hidewall`
1831 AND NOT `thread`.`private`
1833 AND `thread`.`visible`
1834 AND NOT `thread`.`deleted`
1835 AND NOT `thread`.`moderated`
1836 AND `thread`.`iid` > ?
1838 ORDER BY `thread`.`iid` DESC
1839 LIMIT " . intval($start) . ", " . intval($count),
1844 $r = dba::inArray($r);
1847 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1849 if ($conversation_id > 0) {
1850 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1854 "SELECT " . item_fieldlists() . "
1856 " . item_joins() . "
1857 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1858 AND NOT `user`.`hidewall`
1860 AND NOT `item`.`private`
1862 AND `item`.`visible`
1863 AND NOT `item`.`deleted`
1864 AND NOT `item`.`moderated`
1867 ORDER BY `item`.`id` DESC
1868 LIMIT " . intval($start) . ", " . intval($count),
1873 $r = dba::inArray($r);
1876 $ret = api_format_items($r, $user_info, false, $type);
1878 $data = ['status' => $ret];
1882 $data = api_rss_extra($a, $data, $user_info);
1886 return api_format_data("statuses", $type, $data);
1889 /// @TODO move to top of file or somewhere better
1890 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1893 * Returns the most recent statuses posted by users this node knows about.
1895 * @brief Returns the list of public federated posts this node knows about
1897 * @param string $type Return format: json, xml, atom, rss
1898 * @return array|string
1899 * @throws ForbiddenException
1901 function api_statuses_networkpublic_timeline($type)
1905 if (api_user() === false) {
1906 throw new ForbiddenException();
1909 $user_info = api_get_user($a);
1911 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1912 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1915 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1916 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1920 $start = ($page - 1) * $count;
1924 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1928 "SELECT " . item_fieldlists() . "
1930 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1931 " . item_joins() . "
1932 WHERE `thread`.`uid` = 0
1934 AND NOT `thread`.`private`
1935 AND `thread`.`visible`
1936 AND NOT `thread`.`deleted`
1937 AND NOT `thread`.`moderated`
1938 AND `thread`.`iid` > ?
1940 ORDER BY `thread`.`iid` DESC
1941 LIMIT " . intval($start) . ", " . intval($count),
1946 $r = dba::inArray($r);
1948 $ret = api_format_items($r, $user_info, false, $type);
1950 $data = ['status' => $ret];
1954 $data = api_rss_extra($a, $data, $user_info);
1958 return api_format_data("statuses", $type, $data);
1961 /// @TODO move to top of file or somewhere better
1962 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1965 * Returns a single status.
1967 * @param string $type Return type (atom, rss, xml, json)
1969 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1971 function api_statuses_show($type)
1975 if (api_user() === false) {
1976 throw new ForbiddenException();
1979 $user_info = api_get_user($a);
1982 $id = intval($a->argv[3]);
1985 $id = intval($_REQUEST["id"]);
1990 $id = intval($a->argv[4]);
1993 logger('API: api_statuses_show: ' . $id);
1995 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1998 if ($conversation) {
1999 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
2001 $sql_extra .= " AND `item`.`id` = %d";
2005 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2006 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2007 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2008 `contact`.`id` AS `cid`
2010 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2011 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2012 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2013 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2016 dbesc(ACTIVITY_POST),
2020 /// @TODO How about copying this to above methods which don't check $r ?
2021 if (!DBM::is_result($r)) {
2022 throw new BadRequestException("There is no status with this id.");
2025 $ret = api_format_items($r, $user_info, false, $type);
2027 if ($conversation) {
2028 $data = ['status' => $ret];
2029 return api_format_data("statuses", $type, $data);
2031 $data = ['status' => $ret[0]];
2032 return api_format_data("status", $type, $data);
2036 /// @TODO move to top of file or somewhere better
2037 api_register_func('api/statuses/show', 'api_statuses_show', true);
2041 * @param string $type Return type (atom, rss, xml, json)
2043 * @todo nothing to say?
2045 function api_conversation_show($type)
2049 if (api_user() === false) {
2050 throw new ForbiddenException();
2053 $user_info = api_get_user($a);
2056 $id = intval($a->argv[3]);
2057 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2058 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
2062 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2063 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2065 $start = $page*$count;
2068 $id = intval($_REQUEST["id"]);
2073 $id = intval($a->argv[4]);
2076 logger('API: api_conversation_show: '.$id);
2078 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
2079 if (DBM::is_result($r)) {
2080 $id = $r[0]["parent"];
2086 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2089 // Not sure why this query was so complicated. We should keep it here for a while,
2090 // just to make sure that we really don't need it.
2091 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2092 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2095 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2096 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2097 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2098 `contact`.`id` AS `cid`
2100 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2101 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2102 WHERE `item`.`parent` = %d AND `item`.`visible`
2103 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2104 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2105 AND `item`.`id`>%d $sql_extra
2106 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2109 dbesc(ACTIVITY_POST),
2115 if (!DBM::is_result($r)) {
2116 throw new BadRequestException("There is no status with this id.");
2119 $ret = api_format_items($r, $user_info, false, $type);
2121 $data = ['status' => $ret];
2122 return api_format_data("statuses", $type, $data);
2125 /// @TODO move to top of file or somewhere better
2126 api_register_func('api/conversation/show', 'api_conversation_show', true);
2127 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2132 * @param string $type Return type (atom, rss, xml, json)
2134 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2136 function api_statuses_repeat($type)
2142 if (api_user() === false) {
2143 throw new ForbiddenException();
2149 $id = intval($a->argv[3]);
2152 $id = intval($_REQUEST["id"]);
2157 $id = intval($a->argv[4]);
2160 logger('API: api_statuses_repeat: '.$id);
2163 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2164 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2165 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2166 `contact`.`id` AS `cid`
2168 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2169 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2170 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2171 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2172 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2173 AND `item`.`id`=%d",
2177 /// @TODO other style than above functions!
2178 if (DBM::is_result($r) && $r[0]['body'] != "") {
2179 if (strpos($r[0]['body'], "[/share]") !== false) {
2180 $pos = strpos($r[0]['body'], "[share");
2181 $post = substr($r[0]['body'], $pos);
2183 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2185 $post .= $r[0]['body'];
2186 $post .= "[/share]";
2188 $_REQUEST['body'] = $post;
2189 $_REQUEST['profile_uid'] = api_user();
2190 $_REQUEST['type'] = 'wall';
2191 $_REQUEST['api_source'] = true;
2193 if (!x($_REQUEST, "source")) {
2194 $_REQUEST["source"] = api_source();
2199 throw new ForbiddenException();
2202 // this should output the last post (the one we just posted).
2204 return api_status_show($type);
2207 /// @TODO move to top of file or somewhere better
2208 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2211 * Destroys a specific status.
2213 * @param string $type Return type (atom, rss, xml, json)
2215 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2217 function api_statuses_destroy($type)
2221 if (api_user() === false) {
2222 throw new ForbiddenException();
2228 $id = intval($a->argv[3]);
2231 $id = intval($_REQUEST["id"]);
2236 $id = intval($a->argv[4]);
2239 logger('API: api_statuses_destroy: '.$id);
2241 $ret = api_statuses_show($type);
2243 Item::deleteById($id);
2248 /// @TODO move to top of file or somewhere better
2249 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2252 * Returns the most recent mentions.
2254 * @param string $type Return type (atom, rss, xml, json)
2256 * @see http://developer.twitter.com/doc/get/statuses/mentions
2258 function api_statuses_mentions($type)
2262 if (api_user() === false) {
2263 throw new ForbiddenException();
2266 unset($_REQUEST["user_id"]);
2267 unset($_GET["user_id"]);
2269 unset($_REQUEST["screen_name"]);
2270 unset($_GET["screen_name"]);
2272 $user_info = api_get_user($a);
2273 // get last newtork messages
2277 $since_id = defaults($_REQUEST, 'since_id', 0);
2278 $max_id = defaults($_REQUEST, 'max_id' , 0);
2279 $count = defaults($_REQUEST, 'count' , 20);
2280 $page = defaults($_REQUEST, 'page' , 1);
2285 $start = ($page - 1) * $count;
2287 // Ugly code - should be changed
2288 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2289 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2290 $myurl = str_replace('www.', '', $myurl);
2295 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2299 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2300 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2301 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2302 `contact`.`id` AS `cid`
2303 FROM `item` FORCE INDEX (`uid_id`)
2304 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2305 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2306 WHERE `item`.`uid` = %d AND `verb` = '%s'
2307 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2308 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2309 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2312 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2314 dbesc(ACTIVITY_POST),
2315 dbesc(protect_sprintf($myurl)),
2316 dbesc(protect_sprintf($myurl)),
2323 $ret = api_format_items($r, $user_info, false, $type);
2325 $data = ['status' => $ret];
2329 $data = api_rss_extra($a, $data, $user_info);
2333 return api_format_data("statuses", $type, $data);
2336 /// @TODO move to top of file or somewhere better
2337 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2338 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2341 * Returns the most recent statuses posted by the user.
2343 * @brief Returns a user's public timeline
2345 * @param string $type Either "json" or "xml"
2346 * @return string|array
2347 * @throws ForbiddenException
2348 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2350 function api_statuses_user_timeline($type)
2354 if (api_user() === false) {
2355 throw new ForbiddenException();
2358 $user_info = api_get_user($a);
2361 "api_statuses_user_timeline: api_user: ". api_user() .
2362 "\nuser_info: ".print_r($user_info, true) .
2363 "\n_REQUEST: ".print_r($_REQUEST, true),
2367 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2368 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2369 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2370 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2373 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2374 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2378 $start = ($page - 1) * $count;
2381 if ($user_info['self'] == 1) {
2382 $sql_extra .= " AND `item`.`wall` = 1 ";
2385 if ($exclude_replies > 0) {
2386 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2389 if ($conversation_id > 0) {
2390 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2394 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2398 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2399 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2400 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2401 `contact`.`id` AS `cid`
2402 FROM `item` FORCE INDEX (`uid_contactid_id`)
2403 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2404 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2405 WHERE `item`.`uid` = %d AND `verb` = '%s'
2406 AND `item`.`contact-id` = %d
2407 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2409 AND `item`.`id` > %d
2410 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2412 dbesc(ACTIVITY_POST),
2413 intval($user_info['cid']),
2419 $ret = api_format_items($r, $user_info, true, $type);
2421 $data = ['status' => $ret];
2425 $data = api_rss_extra($a, $data, $user_info);
2429 return api_format_data("statuses", $type, $data);
2432 /// @TODO move to top of file or somewhere better
2433 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2436 * Star/unstar an item.
2437 * param: id : id of the item
2439 * @param string $type Return type (atom, rss, xml, json)
2441 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2443 function api_favorites_create_destroy($type)
2447 if (api_user() === false) {
2448 throw new ForbiddenException();
2451 // for versioned api.
2452 /// @TODO We need a better global soluton
2453 $action_argv_id = 2;
2454 if ($a->argv[1] == "1.1") {
2455 $action_argv_id = 3;
2458 if ($a->argc <= $action_argv_id) {
2459 throw new BadRequestException("Invalid request.");
2461 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2462 if ($a->argc == $action_argv_id + 2) {
2463 $itemid = intval($a->argv[$action_argv_id + 1]);
2465 /// @TODO use x() to check if _REQUEST contains 'id'
2466 $itemid = intval($_REQUEST['id']);
2469 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2471 if (!DBM::is_result($item) || count($item) == 0) {
2472 throw new BadRequestException("Invalid item.");
2477 $item[0]['starred'] = 1;
2480 $item[0]['starred'] = 0;
2483 throw new BadRequestException("Invalid action ".$action);
2486 $r = Item::update(['starred' => $item[0]['starred']], ['id' => $itemid]);
2489 throw new InternalServerErrorException("DB error");
2493 $user_info = api_get_user($a);
2494 $rets = api_format_items($item, $user_info, false, $type);
2497 $data = ['status' => $ret];
2501 $data = api_rss_extra($a, $data, $user_info);
2504 return api_format_data("status", $type, $data);
2507 /// @TODO move to top of file or somewhere better
2508 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2509 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2512 * Returns the most recent favorite statuses.
2514 * @param string $type Return type (atom, rss, xml, json)
2516 * @return string|array
2518 function api_favorites($type)
2524 if (api_user() === false) {
2525 throw new ForbiddenException();
2530 $user_info = api_get_user($a);
2532 // in friendica starred item are private
2533 // return favorites only for self
2534 logger('api_favorites: self:' . $user_info['self']);
2536 if ($user_info['self'] == 0) {
2542 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2543 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2544 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2545 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2550 $start = $page*$count;
2553 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2557 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2558 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2559 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2560 `contact`.`id` AS `cid`
2561 FROM `item`, `contact`
2562 WHERE `item`.`uid` = %d
2563 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2564 AND `item`.`starred` = 1
2565 AND `contact`.`id` = `item`.`contact-id`
2566 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2569 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2576 $ret = api_format_items($r, $user_info, false, $type);
2579 $data = ['status' => $ret];
2583 $data = api_rss_extra($a, $data, $user_info);
2586 return api_format_data("statuses", $type, $data);
2589 /// @TODO move to top of file or somewhere better
2590 api_register_func('api/favorites', 'api_favorites', true);
2594 * @param array $item
2595 * @param array $recipient
2596 * @param array $sender
2600 function api_format_messages($item, $recipient, $sender)
2602 // standard meta information
2604 'id' => $item['id'],
2605 'sender_id' => $sender['id'] ,
2607 'recipient_id' => $recipient['id'],
2608 'created_at' => api_date($item['created']),
2609 'sender_screen_name' => $sender['screen_name'],
2610 'recipient_screen_name' => $recipient['screen_name'],
2611 'sender' => $sender,
2612 'recipient' => $recipient,
2614 'friendica_seen' => $item['seen'],
2615 'friendica_parent_uri' => $item['parent-uri'],
2618 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2619 unset($ret["sender"]["uid"]);
2620 unset($ret["sender"]["self"]);
2621 unset($ret["recipient"]["uid"]);
2622 unset($ret["recipient"]["self"]);
2624 //don't send title to regular StatusNET requests to avoid confusing these apps
2625 if (x($_GET, 'getText')) {
2626 $ret['title'] = $item['title'];
2627 if ($_GET['getText'] == 'html') {
2628 $ret['text'] = BBCode::convert($item['body'], false);
2629 } elseif ($_GET['getText'] == 'plain') {
2630 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2633 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2635 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2636 unset($ret['sender']);
2637 unset($ret['recipient']);
2645 * @param array $item
2649 function api_convert_item($item)
2651 $body = $item['body'];
2652 $attachments = api_get_attachments($body);
2654 // Workaround for ostatus messages where the title is identically to the body
2655 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2656 $statusbody = trim(HTML::toPlaintext($html, 0));
2658 // handle data: images
2659 $statusbody = api_format_items_embeded_images($item, $statusbody);
2661 $statustitle = trim($item['title']);
2663 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2664 $statustext = trim($statusbody);
2666 $statustext = trim($statustitle."\n\n".$statusbody);
2669 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2670 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2673 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2675 // Workaround for clients with limited HTML parser functionality
2676 $search = ["<br>", "<blockquote>", "</blockquote>",
2677 "<h1>", "</h1>", "<h2>", "</h2>",
2678 "<h3>", "</h3>", "<h4>", "</h4>",
2679 "<h5>", "</h5>", "<h6>", "</h6>"];
2680 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2681 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2682 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2683 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2684 $statushtml = str_replace($search, $replace, $statushtml);
2686 if ($item['title'] != "") {
2687 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2691 $oldtext = $statushtml;
2692 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2693 } while ($oldtext != $statushtml);
2695 if (substr($statushtml, 0, 4) == '<br>') {
2696 $statushtml = substr($statushtml, 4);
2699 if (substr($statushtml, 0, -4) == '<br>') {
2700 $statushtml = substr($statushtml, -4);
2703 // feeds without body should contain the link
2704 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2705 $statushtml .= BBCode::convert($item['plink']);
2708 $entities = api_get_entitities($statustext, $body);
2711 "text" => $statustext,
2712 "html" => $statushtml,
2713 "attachments" => $attachments,
2714 "entities" => $entities
2720 * @param string $body
2722 * @return array|false
2724 function api_get_attachments(&$body)
2727 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2729 $URLSearchString = "^\[\]";
2730 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2738 foreach ($images[1] as $image) {
2739 $imagedata = Image::getInfoFromURL($image);
2742 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2746 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2747 foreach ($images[0] as $orig) {
2748 $body = str_replace($orig, "", $body);
2752 return $attachments;
2757 * @param string $text
2758 * @param string $bbcode
2761 * @todo Links at the first character of the post
2763 function api_get_entitities(&$text, $bbcode)
2765 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2767 if ($include_entities != "true") {
2768 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2770 foreach ($images[1] as $image) {
2771 $replace = proxy_url($image);
2772 $text = str_replace($image, $replace, $text);
2777 $bbcode = BBCode::cleanPictureLinks($bbcode);
2779 // Change pure links in text to bbcode uris
2780 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2783 $entities["hashtags"] = [];
2784 $entities["symbols"] = [];
2785 $entities["urls"] = [];
2786 $entities["user_mentions"] = [];
2788 $URLSearchString = "^\[\]";
2790 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2792 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2793 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2794 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2796 $bbcode = preg_replace(
2797 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2798 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2801 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2803 $bbcode = preg_replace(
2804 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2805 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2808 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2810 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2812 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2813 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2816 foreach ($urls[1] as $id => $url) {
2817 //$start = strpos($text, $url, $offset);
2818 $start = iconv_strpos($text, $url, 0, "UTF-8");
2819 if (!($start === false)) {
2820 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2824 ksort($ordered_urls);
2827 //foreach ($urls[1] AS $id=>$url) {
2828 foreach ($ordered_urls as $url) {
2829 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2830 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2832 $display_url = $url["title"];
2834 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2835 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2837 if (strlen($display_url) > 26) {
2838 $display_url = substr($display_url, 0, 25)."…";
2842 //$start = strpos($text, $url, $offset);
2843 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2844 if (!($start === false)) {
2845 $entities["urls"][] = ["url" => $url["url"],
2846 "expanded_url" => $url["url"],
2847 "display_url" => $display_url,
2848 "indices" => [$start, $start+strlen($url["url"])]];
2849 $offset = $start + 1;
2853 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2854 $ordered_images = [];
2855 foreach ($images[1] as $image) {
2856 //$start = strpos($text, $url, $offset);
2857 $start = iconv_strpos($text, $image, 0, "UTF-8");
2858 if (!($start === false)) {
2859 $ordered_images[$start] = $image;
2862 //$entities["media"] = array();
2865 foreach ($ordered_images as $url) {
2866 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2867 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2869 if (strlen($display_url) > 26) {
2870 $display_url = substr($display_url, 0, 25)."…";
2873 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2874 if (!($start === false)) {
2875 $image = Image::getInfoFromURL($url);
2877 // If image cache is activated, then use the following sizes:
2878 // thumb (150), small (340), medium (600) and large (1024)
2879 if (!Config::get("system", "proxy_disabled")) {
2880 $media_url = proxy_url($url);
2883 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2884 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2886 if (($image[0] > 150) || ($image[1] > 150)) {
2887 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2888 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2891 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2892 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2894 if (($image[0] > 600) || ($image[1] > 600)) {
2895 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2896 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2900 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2903 $entities["media"][] = [
2905 "id_str" => (string)$start+1,
2906 "indices" => [$start, $start+strlen($url)],
2907 "media_url" => normalise_link($media_url),
2908 "media_url_https" => $media_url,
2910 "display_url" => $display_url,
2911 "expanded_url" => $url,
2915 $offset = $start + 1;
2924 * @param array $item
2925 * @param string $text
2929 function api_format_items_embeded_images($item, $text)
2931 $text = preg_replace_callback(
2932 '|data:image/([^;]+)[^=]+=*|m',
2933 function () use ($item) {
2934 return System::baseUrl() . '/display/' . $item['guid'];
2942 * @brief return <a href='url'>name</a> as array
2944 * @param string $txt text
2949 function api_contactlink_to_array($txt)
2952 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2953 if ($r && count($match)==3) {
2955 'name' => $match[2],
2969 * @brief return likes, dislikes and attend status for item
2971 * @param array $item array
2972 * @param string $type Return type (atom, rss, xml, json)
2975 * likes => int count,
2976 * dislikes => int count
2978 function api_format_items_activities(&$item, $type = "json")
2987 'attendmaybe' => [],
2992 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2993 intval($item['uid']),
2997 foreach ($items as $i) {
2998 // not used as result should be structured like other user data
2999 //builtin_activity_puller($i, $activities);
3001 // get user data and add it to the array of the activity
3002 $user = api_get_user($a, $i['author-link']);
3003 switch ($i['verb']) {
3005 $activities['like'][] = $user;
3007 case ACTIVITY_DISLIKE:
3008 $activities['dislike'][] = $user;
3010 case ACTIVITY_ATTEND:
3011 $activities['attendyes'][] = $user;
3013 case ACTIVITY_ATTENDNO:
3014 $activities['attendno'][] = $user;
3016 case ACTIVITY_ATTENDMAYBE:
3017 $activities['attendmaybe'][] = $user;
3024 if ($type == "xml") {
3025 $xml_activities = [];
3026 foreach ($activities as $k => $v) {
3027 // change xml element from "like" to "friendica:like"
3028 $xml_activities["friendica:".$k] = $v;
3029 // add user data into xml output
3031 foreach ($v as $user) {
3032 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
3035 $activities = $xml_activities;
3043 * @brief return data from profiles
3045 * @param array $profile_row array containing data from db table 'profile'
3048 function api_format_items_profiles($profile_row)
3051 'profile_id' => $profile_row['id'],
3052 'profile_name' => $profile_row['profile-name'],
3053 'is_default' => $profile_row['is-default'] ? true : false,
3054 'hide_friends' => $profile_row['hide-friends'] ? true : false,
3055 'profile_photo' => $profile_row['photo'],
3056 'profile_thumb' => $profile_row['thumb'],
3057 'publish' => $profile_row['publish'] ? true : false,
3058 'net_publish' => $profile_row['net-publish'] ? true : false,
3059 'description' => $profile_row['pdesc'],
3060 'date_of_birth' => $profile_row['dob'],
3061 'address' => $profile_row['address'],
3062 'city' => $profile_row['locality'],
3063 'region' => $profile_row['region'],
3064 'postal_code' => $profile_row['postal-code'],
3065 'country' => $profile_row['country-name'],
3066 'hometown' => $profile_row['hometown'],
3067 'gender' => $profile_row['gender'],
3068 'marital' => $profile_row['marital'],
3069 'marital_with' => $profile_row['with'],
3070 'marital_since' => $profile_row['howlong'],
3071 'sexual' => $profile_row['sexual'],
3072 'politic' => $profile_row['politic'],
3073 'religion' => $profile_row['religion'],
3074 'public_keywords' => $profile_row['pub_keywords'],
3075 'private_keywords' => $profile_row['prv_keywords'],
3076 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
3077 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
3078 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
3079 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
3080 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
3081 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
3082 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
3083 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
3084 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
3085 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
3086 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
3087 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
3088 'homepage' => $profile_row['homepage'],
3095 * @brief format items to be returned by api
3097 * @param array $r array of items
3098 * @param array $user_info
3099 * @param bool $filter_user filter items by $user_info
3100 * @param string $type Return type (atom, rss, xml, json)
3102 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3108 foreach ($r as $item) {
3109 localize_item($item);
3110 list($status_user, $owner_user) = api_item_get_user($a, $item);
3112 // Look if the posts are matching if they should be filtered by user id
3113 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3117 $in_reply_to = api_in_reply_to($item);
3119 $converted = api_convert_item($item);
3121 if ($type == "xml") {
3122 $geo = "georss:point";
3128 'text' => $converted["text"],
3129 'truncated' => false,
3130 'created_at'=> api_date($item['created']),
3131 'in_reply_to_status_id' => $in_reply_to['status_id'],
3132 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3133 'source' => (($item['app']) ? $item['app'] : 'web'),
3134 'id' => intval($item['id']),
3135 'id_str' => (string) intval($item['id']),
3136 'in_reply_to_user_id' => $in_reply_to['user_id'],
3137 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3138 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3140 'favorited' => $item['starred'] ? true : false,
3141 'user' => $status_user ,
3142 'friendica_owner' => $owner_user,
3143 //'entities' => NULL,
3144 'statusnet_html' => $converted["html"],
3145 'statusnet_conversation_id' => $item['parent'],
3146 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3147 'friendica_activities' => api_format_items_activities($item, $type),
3150 if (count($converted["attachments"]) > 0) {
3151 $status["attachments"] = $converted["attachments"];
3154 if (count($converted["entities"]) > 0) {
3155 $status["entities"] = $converted["entities"];
3158 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3159 $status["source"] = ContactSelector::networkToName($item['item_network'], $user_info['url']);
3160 } elseif (($item['item_network'] != "") && (ContactSelector::networkToName($item['item_network'], $user_info['url']) != $status["source"])) {
3161 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['item_network'], $user_info['url']).')');
3165 // Retweets are only valid for top postings
3166 // It doesn't work reliable with the link if its a feed
3167 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3169 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3172 if ($item["id"] == $item["parent"]) {
3173 $retweeted_item = api_share_as_retweet($item);
3174 if ($retweeted_item !== false) {
3175 $retweeted_status = $status;
3177 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3178 } catch (BadRequestException $e) {
3179 // user not found. should be found?
3180 /// @todo check if the user should be always found
3181 $retweeted_status["user"] = [];
3184 $rt_converted = api_convert_item($retweeted_item);
3186 $retweeted_status['text'] = $rt_converted["text"];
3187 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3188 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3189 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3190 $status['retweeted_status'] = $retweeted_status;
3194 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3195 unset($status["user"]["uid"]);
3196 unset($status["user"]["self"]);
3198 if ($item["coord"] != "") {
3199 $coords = explode(' ', $item["coord"]);
3200 if (count($coords) == 2) {
3201 if ($type == "json") {
3202 $status["geo"] = ['type' => 'Point',
3203 'coordinates' => [(float) $coords[0],
3204 (float) $coords[1]]];
3205 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3206 $status["georss:point"] = $item["coord"];
3216 * Returns the remaining number of API requests available to the user before the API limit is reached.
3218 * @param string $type Return type (atom, rss, xml, json)
3220 * @return array|string
3222 function api_account_rate_limit_status($type)
3224 if ($type == "xml") {
3226 'remaining-hits' => '150',
3227 '@attributes' => ["type" => "integer"],
3228 'hourly-limit' => '150',
3229 '@attributes2' => ["type" => "integer"],
3230 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3231 '@attributes3' => ["type" => "datetime"],
3232 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3233 '@attributes4' => ["type" => "integer"],
3237 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3238 'remaining_hits' => '150',
3239 'hourly_limit' => '150',
3240 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3244 return api_format_data('hash', $type, ['hash' => $hash]);
3247 /// @TODO move to top of file or somewhere better
3248 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3251 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3253 * @param string $type Return type (atom, rss, xml, json)
3255 * @return array|string
3257 function api_help_test($type)
3259 if ($type == 'xml') {
3265 return api_format_data('ok', $type, ["ok" => $ok]);
3268 /// @TODO move to top of file or somewhere better
3269 api_register_func('api/help/test', 'api_help_test', false);
3273 * @param string $type Return type (atom, rss, xml, json)
3275 * @return array|string
3277 function api_lists($type)
3280 /// @TODO $ret is not filled here?
3281 return api_format_data('lists', $type, ["lists_list" => $ret]);
3284 /// @TODO move to top of file or somewhere better
3285 api_register_func('api/lists', 'api_lists', true);
3288 * Returns all lists the user subscribes to.
3290 * @param string $type Return type (atom, rss, xml, json)
3292 * @return array|string
3293 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3295 function api_lists_list($type)
3298 /// @TODO $ret is not filled here?
3299 return api_format_data('lists', $type, ["lists_list" => $ret]);
3302 /// @TODO move to top of file or somewhere better
3303 api_register_func('api/lists/list', 'api_lists_list', true);
3306 * Considers friends and followers lists to be private and won't return
3307 * anything if any user_id parameter is passed.
3309 * @brief Returns either the friends of the follower list
3311 * @param string $qtype Either "friends" or "followers"
3312 * @return boolean|array
3313 * @throws ForbiddenException
3315 function api_statuses_f($qtype)
3319 if (api_user() === false) {
3320 throw new ForbiddenException();
3324 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3325 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3329 $start = ($page - 1) * $count;
3331 $user_info = api_get_user($a);
3333 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3334 /* this is to stop Hotot to load friends multiple times
3335 * I'm not sure if I'm missing return something or
3336 * is a bug in hotot. Workaround, meantime
3340 return array('$users' => $ret);*/
3345 if ($qtype == 'friends') {
3346 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3347 } elseif ($qtype == 'followers') {
3348 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3351 // friends and followers only for self
3352 if ($user_info['self'] == 0) {
3353 $sql_extra = " AND false ";
3356 if ($qtype == 'blocks') {
3357 $sql_filter = 'AND `blocked` AND NOT `pending`';
3358 } elseif ($qtype == 'incoming') {
3359 $sql_filter = 'AND `pending`';
3361 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3379 foreach ($r as $cid) {
3380 $user = api_get_user($a, $cid['nurl']);
3381 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3382 unset($user["uid"]);
3383 unset($user["self"]);
3390 return ['user' => $ret];
3395 * Returns the user's friends.
3397 * @brief Returns the list of friends of the provided user
3399 * @deprecated By Twitter API in favor of friends/list
3401 * @param string $type Either "json" or "xml"
3402 * @return boolean|string|array
3404 function api_statuses_friends($type)
3406 $data = api_statuses_f("friends");
3407 if ($data === false) {
3410 return api_format_data("users", $type, $data);
3414 * Returns the user's followers.
3416 * @brief Returns the list of followers of the provided user
3418 * @deprecated By Twitter API in favor of friends/list
3420 * @param string $type Either "json" or "xml"
3421 * @return boolean|string|array
3423 function api_statuses_followers($type)
3425 $data = api_statuses_f("followers");
3426 if ($data === false) {
3429 return api_format_data("users", $type, $data);
3432 /// @TODO move to top of file or somewhere better
3433 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3434 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3437 * Returns the list of blocked users
3439 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3441 * @param string $type Either "json" or "xml"
3443 * @return boolean|string|array
3445 function api_blocks_list($type)
3447 $data = api_statuses_f('blocks');
3448 if ($data === false) {
3451 return api_format_data("users", $type, $data);
3454 /// @TODO move to top of file or somewhere better
3455 api_register_func('api/blocks/list', 'api_blocks_list', true);
3458 * Returns the list of pending users IDs
3460 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3462 * @param string $type Either "json" or "xml"
3464 * @return boolean|string|array
3466 function api_friendships_incoming($type)
3468 $data = api_statuses_f('incoming');
3469 if ($data === false) {
3474 foreach ($data['user'] as $user) {
3475 $ids[] = $user['id'];
3478 return api_format_data("ids", $type, ['id' => $ids]);
3481 /// @TODO move to top of file or somewhere better
3482 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3485 * Returns the instance's configuration information.
3487 * @param string $type Return type (atom, rss, xml, json)
3489 * @return array|string
3491 function api_statusnet_config($type)
3495 $name = $a->config['sitename'];
3496 $server = $a->get_hostname();
3497 $logo = System::baseUrl() . '/images/friendica-64.png';
3498 $email = $a->config['admin_email'];
3499 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3500 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3501 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3502 if ($a->config['api_import_size']) {
3503 $textlimit = (string) $a->config['api_import_size'];
3505 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3506 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3509 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3510 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3511 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3512 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3513 'shorturllength' => '30',
3515 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3516 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3517 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3518 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3523 return api_format_data('config', $type, ['config' => $config]);
3526 /// @TODO move to top of file or somewhere better
3527 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3528 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3532 * @param string $type Return type (atom, rss, xml, json)
3534 * @return array|string
3536 function api_statusnet_version($type)
3539 $fake_statusnet_version = "0.9.7";
3541 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3544 /// @TODO move to top of file or somewhere better
3545 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3546 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3550 * @param string $type Return type (atom, rss, xml, json)
3552 * @todo use api_format_data() to return data
3554 function api_ff_ids($type)
3557 throw new ForbiddenException();
3564 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3567 "SELECT `pcontact`.`id` FROM `contact`
3568 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3569 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3572 if (!DBM::is_result($r)) {
3577 foreach ($r as $rr) {
3578 if ($stringify_ids) {
3581 $ids[] = intval($rr['id']);
3585 return api_format_data("ids", $type, ['id' => $ids]);
3589 * Returns the ID of every user the user is following.
3591 * @param string $type Return type (atom, rss, xml, json)
3593 * @return array|string
3594 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3596 function api_friends_ids($type)
3598 return api_ff_ids($type);
3602 * Returns the ID of every user following the user.
3604 * @param string $type Return type (atom, rss, xml, json)
3606 * @return array|string
3607 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3609 function api_followers_ids($type)
3611 return api_ff_ids($type);
3614 /// @TODO move to top of file or somewhere better
3615 api_register_func('api/friends/ids', 'api_friends_ids', true);
3616 api_register_func('api/followers/ids', 'api_followers_ids', true);
3619 * Sends a new direct message.
3621 * @param string $type Return type (atom, rss, xml, json)
3623 * @return array|string
3624 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3626 function api_direct_messages_new($type)
3631 if (api_user() === false) {
3632 throw new ForbiddenException();
3635 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3639 $sender = api_get_user($a);
3641 if ($_POST['screen_name']) {
3643 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3645 dbesc($_POST['screen_name'])
3648 // Selecting the id by priority, friendica first
3649 api_best_nickname($r);
3651 $recipient = api_get_user($a, $r[0]['nurl']);
3653 $recipient = api_get_user($a, $_POST['user_id']);
3658 if (x($_REQUEST, 'replyto')) {
3660 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3662 intval($_REQUEST['replyto'])
3664 $replyto = $r[0]['parent-uri'];
3665 $sub = $r[0]['title'];
3667 if (x($_REQUEST, 'title')) {
3668 $sub = $_REQUEST['title'];
3670 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3674 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3677 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3678 $ret = api_format_messages($r[0], $recipient, $sender);
3680 $ret = ["error"=>$id];
3683 $data = ['direct_message'=>$ret];
3688 $data = api_rss_extra($a, $data, $sender);
3691 return api_format_data("direct-messages", $type, $data);
3694 /// @TODO move to top of file or somewhere better
3695 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3698 * Destroys a direct message.
3700 * @brief delete a direct_message from mail table through api
3702 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3704 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3706 function api_direct_messages_destroy($type)
3710 if (api_user() === false) {
3711 throw new ForbiddenException();
3715 $user_info = api_get_user($a);
3717 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3719 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3720 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3721 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3723 $uid = $user_info['uid'];
3724 // error if no id or parenturi specified (for clients posting parent-uri as well)
3725 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3726 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3727 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3730 // BadRequestException if no id specified (for clients using Twitter API)
3732 throw new BadRequestException('Message id not specified');
3735 // add parent-uri to sql command if specified by calling app
3736 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3738 // get data of the specified message id
3740 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3745 // error message if specified id is not in database
3746 if (!DBM::is_result($r)) {
3747 if ($verbose == "true") {
3748 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3749 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3751 /// @todo BadRequestException ok for Twitter API clients?
3752 throw new BadRequestException('message id not in database');
3757 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3762 if ($verbose == "true") {
3765 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3766 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3768 $answer = ['result' => 'error', 'message' => 'unknown error'];
3769 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3772 /// @todo return JSON data like Twitter API not yet implemented
3775 /// @TODO move to top of file or somewhere better
3776 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3780 * @param string $type Return type (atom, rss, xml, json)
3781 * @param string $box
3782 * @param string $verbose
3784 * @return array|string
3786 function api_direct_messages_box($type, $box, $verbose)
3790 if (api_user() === false) {
3791 throw new ForbiddenException();
3795 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3796 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3801 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3802 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3804 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3805 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3808 unset($_REQUEST["user_id"]);
3809 unset($_GET["user_id"]);
3811 unset($_REQUEST["screen_name"]);
3812 unset($_GET["screen_name"]);
3814 $user_info = api_get_user($a);
3815 $profile_url = $user_info["url"];
3818 $start = $page * $count;
3823 if ($box=="sentbox") {
3824 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3825 } elseif ($box == "conversation") {
3826 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3827 } elseif ($box == "all") {
3828 $sql_extra = "true";
3829 } elseif ($box == "inbox") {
3830 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3834 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3837 if ($user_id != "") {
3838 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3839 } elseif ($screen_name !="") {
3840 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3844 "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",
3850 if ($verbose == "true" && !DBM::is_result($r)) {
3851 $answer = ['result' => 'error', 'message' => 'no mails available'];
3852 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3856 foreach ($r as $item) {
3857 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3858 $recipient = $user_info;
3859 $sender = api_get_user($a, normalise_link($item['contact-url']));
3860 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3861 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3862 $sender = $user_info;
3865 $ret[] = api_format_messages($item, $recipient, $sender);
3869 $data = ['direct_message' => $ret];
3873 $data = api_rss_extra($a, $data, $user_info);
3876 return api_format_data("direct-messages", $type, $data);
3880 * Returns the most recent direct messages sent by the user.
3882 * @param string $type Return type (atom, rss, xml, json)
3884 * @return array|string
3885 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3887 function api_direct_messages_sentbox($type)
3889 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3890 return api_direct_messages_box($type, "sentbox", $verbose);
3894 * Returns the most recent direct messages sent to the user.
3896 * @param string $type Return type (atom, rss, xml, json)
3898 * @return array|string
3899 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3901 function api_direct_messages_inbox($type)
3903 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3904 return api_direct_messages_box($type, "inbox", $verbose);
3909 * @param string $type Return type (atom, rss, xml, json)
3911 * @return array|string
3913 function api_direct_messages_all($type)
3915 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3916 return api_direct_messages_box($type, "all", $verbose);
3921 * @param string $type Return type (atom, rss, xml, json)
3923 * @return array|string
3925 function api_direct_messages_conversation($type)
3927 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3928 return api_direct_messages_box($type, "conversation", $verbose);
3931 /// @TODO move to top of file or somewhere better
3932 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3933 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3934 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3935 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3938 * Returns an OAuth Request Token.
3940 * @see https://oauth.net/core/1.0/#auth_step1
3942 function api_oauth_request_token()
3944 $oauth1 = new FKOAuth1();
3946 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3947 } catch (Exception $e) {
3948 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3956 * Returns an OAuth Access Token.
3958 * @return array|string
3959 * @see https://oauth.net/core/1.0/#auth_step3
3961 function api_oauth_access_token()
3963 $oauth1 = new FKOAuth1();
3965 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3966 } catch (Exception $e) {
3967 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3974 /// @TODO move to top of file or somewhere better
3975 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3976 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3980 * @brief delete a complete photoalbum with all containing photos from database through api
3982 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3985 function api_fr_photoalbum_delete($type)
3987 if (api_user() === false) {
3988 throw new ForbiddenException();
3991 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3993 // we do not allow calls without album string
3995 throw new BadRequestException("no albumname specified");
3997 // check if album is existing
3999 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4003 if (!DBM::is_result($r)) {
4004 throw new BadRequestException("album not available");
4007 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4008 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4009 foreach ($r as $rr) {
4011 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4012 intval(local_user()),
4013 dbesc($rr['resource-id'])
4016 if (!DBM::is_result($photo_item)) {
4017 throw new InternalServerErrorException("problem with deleting items occured");
4019 Item::deleteById($photo_item[0]['id']);
4022 // now let's delete all photos from the album
4023 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
4025 // return success of deletion or error message
4027 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4028 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4030 throw new InternalServerErrorException("unknown error - deleting from database failed");
4035 * @brief update the name of the album for all photos of an album
4037 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4040 function api_fr_photoalbum_update($type)
4042 if (api_user() === false) {
4043 throw new ForbiddenException();
4046 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4047 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4049 // we do not allow calls without album string
4051 throw new BadRequestException("no albumname specified");
4053 if ($album_new == "") {
4054 throw new BadRequestException("no new albumname specified");
4056 // check if album is existing
4058 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4062 if (!DBM::is_result($r)) {
4063 throw new BadRequestException("album not available");
4065 // now let's update all photos to the albumname
4067 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
4073 // return success of updating or error message
4075 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4076 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4078 throw new InternalServerErrorException("unknown error - updating in database failed");
4084 * @brief list all photos of the authenticated user
4086 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4089 function api_fr_photos_list($type)
4091 if (api_user() === false) {
4092 throw new ForbiddenException();
4095 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4096 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4097 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4098 intval(local_user())
4101 'image/jpeg' => 'jpg',
4102 'image/png' => 'png',
4103 'image/gif' => 'gif'
4105 $data = ['photo'=>[]];
4106 if (DBM::is_result($r)) {
4107 foreach ($r as $rr) {
4109 $photo['id'] = $rr['resource-id'];
4110 $photo['album'] = $rr['album'];
4111 $photo['filename'] = $rr['filename'];
4112 $photo['type'] = $rr['type'];
4113 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4114 $photo['created'] = $rr['created'];
4115 $photo['edited'] = $rr['edited'];
4116 $photo['desc'] = $rr['desc'];
4118 if ($type == "xml") {
4119 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4121 $photo['thumb'] = $thumb;
4122 $data['photo'][] = $photo;
4126 return api_format_data("photos", $type, $data);
4130 * @brief upload a new photo or change an existing photo
4132 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4135 function api_fr_photo_create_update($type)
4137 if (api_user() === false) {
4138 throw new ForbiddenException();
4141 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4142 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4143 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4144 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4145 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4146 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4147 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4148 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4149 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4151 // do several checks on input parameters
4152 // we do not allow calls without album string
4153 if ($album == null) {
4154 throw new BadRequestException("no albumname specified");
4156 // if photo_id == null --> we are uploading a new photo
4157 if ($photo_id == null) {
4160 // error if no media posted in create-mode
4161 if (!x($_FILES, 'media')) {
4163 throw new BadRequestException("no media data submitted");
4166 // album_new will be ignored in create-mode
4171 // check if photo is existing in database
4173 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4178 if (!DBM::is_result($r)) {
4179 throw new BadRequestException("photo not available");
4183 // checks on acl strings provided by clients
4184 $acl_input_error = false;
4185 $acl_input_error |= check_acl_input($allow_cid);
4186 $acl_input_error |= check_acl_input($deny_cid);
4187 $acl_input_error |= check_acl_input($allow_gid);
4188 $acl_input_error |= check_acl_input($deny_gid);
4189 if ($acl_input_error) {
4190 throw new BadRequestException("acl data invalid");
4192 // now let's upload the new media in create-mode
4193 if ($mode == "create") {
4194 $media = $_FILES['media'];
4195 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4197 // return success of updating or error message
4198 if (!is_null($data)) {
4199 return api_format_data("photo_create", $type, $data);
4201 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4205 // now let's do the changes in update-mode
4206 if ($mode == "update") {
4209 if (!is_null($desc)) {
4210 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4213 if (!is_null($album_new)) {
4214 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4217 if (!is_null($allow_cid)) {
4218 $allow_cid = trim($allow_cid);
4219 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4222 if (!is_null($deny_cid)) {
4223 $deny_cid = trim($deny_cid);
4224 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4227 if (!is_null($allow_gid)) {
4228 $allow_gid = trim($allow_gid);
4229 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4232 if (!is_null($deny_gid)) {
4233 $deny_gid = trim($deny_gid);
4234 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4238 if ($sql_extra != "") {
4239 $nothingtodo = false;
4241 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4243 DateTimeFormat::utcNow(), // update edited timestamp
4249 $nothingtodo = true;
4252 if (x($_FILES, 'media')) {
4253 $nothingtodo = false;
4254 $media = $_FILES['media'];
4255 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4256 if (!is_null($data)) {
4257 return api_format_data("photo_update", $type, $data);
4261 // return success of updating or error message
4263 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4264 return api_format_data("photo_update", $type, ['$result' => $answer]);
4267 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4268 return api_format_data("photo_update", $type, ['$result' => $answer]);
4270 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4273 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4278 * @brief delete a single photo from the database through api
4280 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4283 function api_fr_photo_delete($type)
4285 if (api_user() === false) {
4286 throw new ForbiddenException();
4289 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4291 // do several checks on input parameters
4292 // we do not allow calls without photo id
4293 if ($photo_id == null) {
4294 throw new BadRequestException("no photo_id specified");
4296 // check if photo is existing in database
4298 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4302 if (!DBM::is_result($r)) {
4303 throw new BadRequestException("photo not available");
4305 // now we can perform on the deletion of the photo
4306 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4308 // return success of deletion or error message
4310 // retrieve the id of the parent element (the photo element)
4312 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4313 intval(local_user()),
4317 if (!DBM::is_result($photo_item)) {
4318 throw new InternalServerErrorException("problem with deleting items occured");
4320 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4321 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4322 Item::deleteById($photo_item[0]['id']);
4324 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4325 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4327 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4333 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4335 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4336 * @return string|array
4338 function api_fr_photo_detail($type)
4340 if (api_user() === false) {
4341 throw new ForbiddenException();
4343 if (!x($_REQUEST, 'photo_id')) {
4344 throw new BadRequestException("No photo id.");
4347 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4348 $photo_id = $_REQUEST['photo_id'];
4350 // prepare json/xml output with data from database for the requested photo
4351 $data = prepare_photo_data($type, $scale, $photo_id);
4353 return api_format_data("photo_detail", $type, $data);
4358 * Updates the user’s profile image.
4360 * @brief updates the profile image for the user (either a specified profile or the default profile)
4362 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4365 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4367 function api_account_update_profile_image($type)
4369 if (api_user() === false) {
4370 throw new ForbiddenException();
4373 $profileid = defaults($_REQUEST, 'profile_id', 0);
4375 // error if image data is missing
4376 if (!x($_FILES, 'image')) {
4377 throw new BadRequestException("no media data submitted");
4380 // check if specified profile id is valid
4381 if ($profileid != 0) {
4383 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4387 // error message if specified profile id is not in database
4388 if (!DBM::is_result($r)) {
4389 throw new BadRequestException("profile_id not available");
4391 $is_default_profile = $r['profile'];
4393 $is_default_profile = 1;
4396 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4398 if (x($_FILES, 'image')) {
4399 $media = $_FILES['image'];
4400 } elseif (x($_FILES, 'media')) {
4401 $media = $_FILES['media'];
4403 // save new profile image
4404 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4407 if (is_array($media['type'])) {
4408 $filetype = $media['type'][0];
4410 $filetype = $media['type'];
4412 if ($filetype == "image/jpeg") {
4414 } elseif ($filetype == "image/png") {
4417 // change specified profile or all profiles to the new resource-id
4418 if ($is_default_profile) {
4420 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4421 dbesc($data['photo']['id']),
4422 intval(local_user())
4426 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4427 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4428 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4429 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4430 intval(local_user())
4434 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4435 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4436 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4437 intval($_REQUEST['profile']),
4438 intval(local_user())
4442 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4443 // so that browsers will do a cache update unconditionally
4446 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4447 dbesc(DateTimeFormat::utcNow()),
4448 intval(local_user())
4451 // Update global directory in background
4452 //$user = api_get_user(get_app());
4453 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4454 if ($url && strlen(Config::get('system', 'directory'))) {
4455 Worker::add(PRIORITY_LOW, "Directory", $url);
4458 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4460 // output for client
4462 return api_account_verify_credentials($type);
4464 // SaveMediaToDatabase failed for some reason
4465 throw new InternalServerErrorException("image upload failed");
4469 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4470 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4471 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4472 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4473 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4474 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4475 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4476 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4477 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4480 * Update user profile
4482 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4484 * @return array|string
4486 function api_account_update_profile($type)
4488 $local_user = api_user();
4489 $api_user = api_get_user(get_app());
4491 if (!empty($_POST['name'])) {
4492 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4493 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4494 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4495 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4498 if (isset($_POST['description'])) {
4499 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4500 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4501 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4504 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4505 // Update global directory in background
4506 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4507 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4510 return api_account_verify_credentials($type);
4513 /// @TODO move to top of file or somewhere better
4514 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4518 * @param string $acl_string
4520 function check_acl_input($acl_string)
4522 if ($acl_string == null || $acl_string == " ") {
4525 $contact_not_found = false;
4527 // split <x><y><z> into array of cid's
4528 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4530 // check for each cid if it is available on server
4531 $cid_array = $array[0];
4532 foreach ($cid_array as $cid) {
4533 $cid = str_replace("<", "", $cid);
4534 $cid = str_replace(">", "", $cid);
4536 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4540 $contact_not_found |= !DBM::is_result($contact);
4542 return $contact_not_found;
4547 * @param string $mediatype
4548 * @param array $media
4549 * @param string $type
4550 * @param string $album
4551 * @param string $allow_cid
4552 * @param string $deny_cid
4553 * @param string $allow_gid
4554 * @param string $deny_gid
4555 * @param string $desc
4556 * @param integer $profile
4557 * @param boolean $visibility
4558 * @param string $photo_id
4560 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)
4568 if (is_array($media)) {
4569 if (is_array($media['tmp_name'])) {
4570 $src = $media['tmp_name'][0];
4572 $src = $media['tmp_name'];
4574 if (is_array($media['name'])) {
4575 $filename = basename($media['name'][0]);
4577 $filename = basename($media['name']);
4579 if (is_array($media['size'])) {
4580 $filesize = intval($media['size'][0]);
4582 $filesize = intval($media['size']);
4584 if (is_array($media['type'])) {
4585 $filetype = $media['type'][0];
4587 $filetype = $media['type'];
4591 if ($filetype == "") {
4592 $filetype=Image::guessType($filename);
4594 $imagedata = getimagesize($src);
4596 $filetype = $imagedata['mime'];
4599 "File upload src: " . $src . " - filename: " . $filename .
4600 " - size: " . $filesize . " - type: " . $filetype,
4604 // check if there was a php upload error
4605 if ($filesize == 0 && $media['error'] == 1) {
4606 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4608 // check against max upload size within Friendica instance
4609 $maximagesize = Config::get('system', 'maximagesize');
4610 if ($maximagesize && ($filesize > $maximagesize)) {
4611 $formattedBytes = formatBytes($maximagesize);
4612 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4615 // create Photo instance with the data of the image
4616 $imagedata = @file_get_contents($src);
4617 $Image = new Image($imagedata, $filetype);
4618 if (! $Image->isValid()) {
4619 throw new InternalServerErrorException("unable to process image data");
4622 // check orientation of image
4623 $Image->orient($src);
4626 // check max length of images on server
4627 $max_length = Config::get('system', 'max_image_length');
4628 if (! $max_length) {
4629 $max_length = MAX_IMAGE_LENGTH;
4631 if ($max_length > 0) {
4632 $Image->scaleDown($max_length);
4633 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4635 $width = $Image->getWidth();
4636 $height = $Image->getHeight();
4638 // create a new resource-id if not already provided
4639 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4641 if ($mediatype == "photo") {
4642 // upload normal image (scales 0, 1, 2)
4643 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4645 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4647 logger("photo upload: image upload with scale 0 (original size) failed");
4649 if ($width > 640 || $height > 640) {
4650 $Image->scaleDown(640);
4651 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4653 logger("photo upload: image upload with scale 1 (640x640) failed");
4657 if ($width > 320 || $height > 320) {
4658 $Image->scaleDown(320);
4659 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4661 logger("photo upload: image upload with scale 2 (320x320) failed");
4664 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4665 } elseif ($mediatype == "profileimage") {
4666 // upload profile image (scales 4, 5, 6)
4667 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4669 if ($width > 175 || $height > 175) {
4670 $Image->scaleDown(175);
4671 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4673 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4677 if ($width > 80 || $height > 80) {
4678 $Image->scaleDown(80);
4679 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4681 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4685 if ($width > 48 || $height > 48) {
4686 $Image->scaleDown(48);
4687 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4689 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4692 $Image->__destruct();
4693 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4697 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4698 if ($photo_id == null && $mediatype == "photo") {
4699 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4701 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4702 return prepare_photo_data($type, false, $hash);
4704 throw new InternalServerErrorException("image upload failed");
4710 * @param string $hash
4711 * @param string $allow_cid
4712 * @param string $deny_cid
4713 * @param string $allow_gid
4714 * @param string $deny_gid
4715 * @param string $filetype
4716 * @param boolean $visibility
4718 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4720 // get data about the api authenticated user
4721 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4722 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4725 $arr['guid'] = get_guid(32);
4726 $arr['uid'] = intval(api_user());
4728 $arr['parent-uri'] = $uri;
4729 $arr['type'] = 'photo';
4731 $arr['resource-id'] = $hash;
4732 $arr['contact-id'] = $owner_record[0]['id'];
4733 $arr['owner-name'] = $owner_record[0]['name'];
4734 $arr['owner-link'] = $owner_record[0]['url'];
4735 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4736 $arr['author-name'] = $owner_record[0]['name'];
4737 $arr['author-link'] = $owner_record[0]['url'];
4738 $arr['author-avatar'] = $owner_record[0]['thumb'];
4740 $arr['allow_cid'] = $allow_cid;
4741 $arr['allow_gid'] = $allow_gid;
4742 $arr['deny_cid'] = $deny_cid;
4743 $arr['deny_gid'] = $deny_gid;
4744 $arr['visible'] = $visibility;
4748 'image/jpeg' => 'jpg',
4749 'image/png' => 'png',
4750 'image/gif' => 'gif'
4753 // adds link to the thumbnail scale photo
4754 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4755 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4758 // do the magic for storing the item in the database and trigger the federation to other contacts
4764 * @param string $type
4766 * @param string $photo_id
4770 function prepare_photo_data($type, $scale, $photo_id)
4772 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4773 $data_sql = ($scale === false ? "" : "data, ");
4775 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4776 // clients needs to convert this in their way for further processing
4778 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4779 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4780 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4781 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4783 intval(local_user()),
4789 'image/jpeg' => 'jpg',
4790 'image/png' => 'png',
4791 'image/gif' => 'gif'
4794 // prepare output data for photo
4795 if (DBM::is_result($r)) {
4796 $data = ['photo' => $r[0]];
4797 $data['photo']['id'] = $data['photo']['resource-id'];
4798 if ($scale !== false) {
4799 $data['photo']['data'] = base64_encode($data['photo']['data']);
4801 unset($data['photo']['datasize']); //needed only with scale param
4803 if ($type == "xml") {
4804 $data['photo']['links'] = [];
4805 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4806 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4808 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4811 $data['photo']['link'] = [];
4812 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4814 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4815 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4819 unset($data['photo']['resource-id']);
4820 unset($data['photo']['minscale']);
4821 unset($data['photo']['maxscale']);
4823 throw new NotFoundException();
4826 // retrieve item element for getting activities (like, dislike etc.) related to photo
4828 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4829 intval(local_user()),
4832 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4834 // retrieve comments on photo
4836 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4837 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4838 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4839 `contact`.`id` AS `cid`
4841 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4842 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4843 WHERE `item`.`parent` = %d AND `item`.`visible`
4844 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4845 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4846 intval($item[0]['parent']),
4848 dbesc(ACTIVITY_POST)
4851 // prepare output of comments
4852 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4854 if ($type == "xml") {
4856 foreach ($commentData as $comment) {
4857 $comments[$k++ . ":comment"] = $comment;
4860 foreach ($commentData as $comment) {
4861 $comments[] = $comment;
4864 $data['photo']['friendica_comments'] = $comments;
4866 // include info if rights on photo and rights on item are mismatching
4867 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4868 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4869 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4870 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4871 $data['photo']['rights_mismatch'] = $rights_mismatch;
4878 * Similar as /mod/redir.php
4879 * redirect to 'url' after dfrn auth
4881 * Why this when there is mod/redir.php already?
4882 * This use api_user() and api_login()
4885 * c_url: url of remote contact to auth to
4886 * url: string, url to redirect after auth
4888 function api_friendica_remoteauth()
4890 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4891 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4893 if ($url === '' || $c_url === '') {
4894 throw new BadRequestException("Wrong parameters.");
4897 $c_url = normalise_link($c_url);
4901 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4903 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4904 throw new BadRequestException("Unknown contact");
4907 $cid = $contact['id'];
4909 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4911 if ($contact['duplex'] && $contact['issued-id']) {
4912 $orig_id = $contact['issued-id'];
4913 $dfrn_id = '1:' . $orig_id;
4915 if ($contact['duplex'] && $contact['dfrn-id']) {
4916 $orig_id = $contact['dfrn-id'];
4917 $dfrn_id = '0:' . $orig_id;
4920 $sec = random_string();
4923 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4924 VALUES( %d, %s, '%s', '%s', %d )",
4932 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4933 $dest = ($url ? '&destination_url=' . $url : '');
4935 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4936 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4937 . '&type=profile&sec=' . $sec . $dest
4940 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4943 * @brief Return the item shared, if the item contains only the [share] tag
4945 * @param array $item Sharer item
4946 * @return array|false Shared item or false if not a reshare
4948 function api_share_as_retweet(&$item)
4950 $body = trim($item["body"]);
4952 if (Diaspora::isReshare($body, false)===false) {
4956 /// @TODO "$1" should maybe mean '$1' ?
4957 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4959 * Skip if there is no shared message in there
4960 * we already checked this in diaspora::isReshare()
4961 * but better one more than one less...
4963 if ($body == $attributes) {
4968 // build the fake reshared item
4969 $reshared_item = $item;
4972 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4973 if ($matches[1] != "") {
4974 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4977 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4978 if ($matches[1] != "") {
4979 $author = $matches[1];
4983 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4984 if ($matches[1] != "") {
4985 $profile = $matches[1];
4988 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4989 if ($matches[1] != "") {
4990 $profile = $matches[1];
4994 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4995 if ($matches[1] != "") {
4996 $avatar = $matches[1];
4999 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5000 if ($matches[1] != "") {
5001 $avatar = $matches[1];
5005 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5006 if ($matches[1] != "") {
5007 $link = $matches[1];
5010 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5011 if ($matches[1] != "") {
5012 $link = $matches[1];
5016 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5017 if ($matches[1] != "") {
5018 $posted = $matches[1];
5021 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5022 if ($matches[1] != "") {
5023 $posted = $matches[1];
5026 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5028 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5032 $reshared_item["body"] = $shared_body;
5033 $reshared_item["author-name"] = $author;
5034 $reshared_item["author-link"] = $profile;
5035 $reshared_item["author-avatar"] = $avatar;
5036 $reshared_item["plink"] = $link;
5037 $reshared_item["created"] = $posted;
5038 $reshared_item["edited"] = $posted;
5040 return $reshared_item;
5045 * @param string $profile
5047 * @return string|false
5048 * @todo remove trailing junk from profile url
5049 * @todo pump.io check has to check the website
5051 function api_get_nick($profile)
5056 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5057 dbesc(normalise_link($profile))
5060 if (DBM::is_result($r)) {
5061 $nick = $r[0]["nick"];
5066 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5067 dbesc(normalise_link($profile))
5070 if (DBM::is_result($r)) {
5071 $nick = $r[0]["nick"];
5076 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5077 if ($friendica != $profile) {
5083 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5084 if ($diaspora != $profile) {
5090 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5091 if ($twitter != $profile) {
5098 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5099 if ($StatusnetHost != $profile) {
5100 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5101 if ($StatusnetUser != $profile) {
5102 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5103 $user = json_decode($UserData);
5105 $nick = $user->screen_name;
5111 // To-Do: look at the page if its really a pumpio site
5112 //if (!$nick == "") {
5113 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5114 // if ($pumpio != $profile)
5116 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5129 * @param array $item
5133 function api_in_reply_to($item)
5137 $in_reply_to['status_id'] = null;
5138 $in_reply_to['user_id'] = null;
5139 $in_reply_to['status_id_str'] = null;
5140 $in_reply_to['user_id_str'] = null;
5141 $in_reply_to['screen_name'] = null;
5143 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5145 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5146 intval($item['uid']),
5147 dbesc($item['thr-parent'])
5150 if (DBM::is_result($r)) {
5151 $in_reply_to['status_id'] = intval($r[0]['id']);
5153 $in_reply_to['status_id'] = intval($item['parent']);
5156 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5159 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
5160 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5161 WHERE `item`.`id` = %d LIMIT 1",
5162 intval($in_reply_to['status_id'])
5165 if (DBM::is_result($r)) {
5166 if ($r[0]['nick'] == "") {
5167 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5170 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5171 $in_reply_to['user_id'] = intval($r[0]['id']);
5172 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5175 // There seems to be situation, where both fields are identical:
5176 // https://github.com/friendica/friendica/issues/1010
5177 // This is a bugfix for that.
5178 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5179 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5180 $in_reply_to['status_id'] = null;
5181 $in_reply_to['user_id'] = null;
5182 $in_reply_to['status_id_str'] = null;
5183 $in_reply_to['user_id_str'] = null;
5184 $in_reply_to['screen_name'] = null;
5188 return $in_reply_to;
5193 * @param string $Text
5197 function api_clean_plain_items($Text)
5199 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5201 $Text = BBCode::cleanPictureLinks($Text);
5202 $URLSearchString = "^\[\]";
5204 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
5206 if ($include_entities == "true") {
5207 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
5210 // Simplify "attachment" element
5211 $Text = api_clean_attachments($Text);
5217 * @brief Removes most sharing information for API text export
5219 * @param string $body The original body
5221 * @return string Cleaned body
5223 function api_clean_attachments($body)
5225 $data = BBCode::getAttachmentData($body);
5232 if (isset($data["text"])) {
5233 $body = $data["text"];
5235 if (($body == "") && isset($data["title"])) {
5236 $body = $data["title"];
5238 if (isset($data["url"])) {
5239 $body .= "\n".$data["url"];
5241 $body .= $data["after"];
5248 * @param array $contacts
5252 function api_best_nickname(&$contacts)
5256 if (count($contacts) == 0) {
5260 foreach ($contacts as $contact) {
5261 if ($contact["network"] == "") {
5262 $contact["network"] = "dfrn";
5263 $best_contact = [$contact];
5267 if (sizeof($best_contact) == 0) {
5268 foreach ($contacts as $contact) {
5269 if ($contact["network"] == "dfrn") {
5270 $best_contact = [$contact];
5275 if (sizeof($best_contact) == 0) {
5276 foreach ($contacts as $contact) {
5277 if ($contact["network"] == "dspr") {
5278 $best_contact = [$contact];
5283 if (sizeof($best_contact) == 0) {
5284 foreach ($contacts as $contact) {
5285 if ($contact["network"] == "stat") {
5286 $best_contact = [$contact];
5291 if (sizeof($best_contact) == 0) {
5292 foreach ($contacts as $contact) {
5293 if ($contact["network"] == "pump") {
5294 $best_contact = [$contact];
5299 if (sizeof($best_contact) == 0) {
5300 foreach ($contacts as $contact) {
5301 if ($contact["network"] == "twit") {
5302 $best_contact = [$contact];
5307 if (sizeof($best_contact) == 1) {
5308 $contacts = $best_contact;
5310 $contacts = [$contacts[0]];
5315 * Return all or a specified group of the user with the containing contacts.
5317 * @param string $type Return type (atom, rss, xml, json)
5319 * @return array|string
5321 function api_friendica_group_show($type)
5325 if (api_user() === false) {
5326 throw new ForbiddenException();
5330 $user_info = api_get_user($a);
5331 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5332 $uid = $user_info['uid'];
5334 // get data of the specified group id or all groups if not specified
5337 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5341 // error message if specified gid is not in database
5342 if (!DBM::is_result($r)) {
5343 throw new BadRequestException("gid not available");
5347 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5352 // loop through all groups and retrieve all members for adding data in the user array
5353 foreach ($r as $rr) {
5354 $members = Contact::getByGroupId($rr['id']);
5357 if ($type == "xml") {
5358 $user_element = "users";
5360 foreach ($members as $member) {
5361 $user = api_get_user($a, $member['nurl']);
5362 $users[$k++.":user"] = $user;
5365 $user_element = "user";
5366 foreach ($members as $member) {
5367 $user = api_get_user($a, $member['nurl']);
5371 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5373 return api_format_data("groups", $type, ['group' => $grps]);
5375 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5379 * Delete the specified group of the user.
5381 * @param string $type Return type (atom, rss, xml, json)
5383 * @return array|string
5385 function api_friendica_group_delete($type)
5389 if (api_user() === false) {
5390 throw new ForbiddenException();
5394 $user_info = api_get_user($a);
5395 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5396 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5397 $uid = $user_info['uid'];
5399 // error if no gid specified
5400 if ($gid == 0 || $name == "") {
5401 throw new BadRequestException('gid or name not specified');
5404 // get data of the specified group id
5406 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5410 // error message if specified gid is not in database
5411 if (!DBM::is_result($r)) {
5412 throw new BadRequestException('gid not available');
5415 // get data of the specified group id and group name
5417 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5422 // error message if specified gid is not in database
5423 if (!DBM::is_result($rname)) {
5424 throw new BadRequestException('wrong group name');
5428 $ret = Group::removeByName($uid, $name);
5431 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5432 return api_format_data("group_delete", $type, ['result' => $success]);
5434 throw new BadRequestException('other API error');
5437 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5441 * Create the specified group with the posted array of contacts.
5443 * @param string $type Return type (atom, rss, xml, json)
5445 * @return array|string
5447 function api_friendica_group_create($type)
5451 if (api_user() === false) {
5452 throw new ForbiddenException();
5456 $user_info = api_get_user($a);
5457 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5458 $uid = $user_info['uid'];
5459 $json = json_decode($_POST['json'], true);
5460 $users = $json['user'];
5462 // error if no name specified
5464 throw new BadRequestException('group name not specified');
5467 // get data of the specified group name
5469 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5473 // error message if specified group name already exists
5474 if (DBM::is_result($rname)) {
5475 throw new BadRequestException('group name already exists');
5478 // check if specified group name is a deleted group
5480 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5484 // error message if specified group name already exists
5485 if (DBM::is_result($rname)) {
5486 $reactivate_group = true;
5490 $ret = Group::create($uid, $name);
5492 $gid = Group::getIdByName($uid, $name);
5494 throw new BadRequestException('other API error');
5498 $erroraddinguser = false;
5500 foreach ($users as $user) {
5501 $cid = $user['cid'];
5502 // check if user really exists as contact
5504 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5508 if (count($contact)) {
5509 Group::addMember($gid, $cid);
5511 $erroraddinguser = true;
5512 $errorusers[] = $cid;
5516 // return success message incl. missing users in array
5517 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5518 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5519 return api_format_data("group_create", $type, ['result' => $success]);
5521 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5525 * Update the specified group with the posted array of contacts.
5527 * @param string $type Return type (atom, rss, xml, json)
5529 * @return array|string
5531 function api_friendica_group_update($type)
5535 if (api_user() === false) {
5536 throw new ForbiddenException();
5540 $user_info = api_get_user($a);
5541 $uid = $user_info['uid'];
5542 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5543 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5544 $json = json_decode($_POST['json'], true);
5545 $users = $json['user'];
5547 // error if no name specified
5549 throw new BadRequestException('group name not specified');
5552 // error if no gid specified
5554 throw new BadRequestException('gid not specified');
5558 $members = Contact::getByGroupId($gid);
5559 foreach ($members as $member) {
5560 $cid = $member['id'];
5561 foreach ($users as $user) {
5562 $found = ($user['cid'] == $cid ? true : false);
5565 Group::removeMemberByName($uid, $name, $cid);
5570 $erroraddinguser = false;
5572 foreach ($users as $user) {
5573 $cid = $user['cid'];
5574 // check if user really exists as contact
5576 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5581 if (count($contact)) {
5582 Group::addMember($gid, $cid);
5584 $erroraddinguser = true;
5585 $errorusers[] = $cid;
5589 // return success message incl. missing users in array
5590 $status = ($erroraddinguser ? "missing user" : "ok");
5591 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5592 return api_format_data("group_update", $type, ['result' => $success]);
5595 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5599 * @param string $type Return type (atom, rss, xml, json)
5601 * @return array|string
5603 function api_friendica_activity($type)
5607 if (api_user() === false) {
5608 throw new ForbiddenException();
5610 $verb = strtolower($a->argv[3]);
5611 $verb = preg_replace("|\..*$|", "", $verb);
5613 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5615 $res = Item::performLike($id, $verb);
5618 if ($type == "xml") {
5623 return api_format_data('ok', $type, ['ok' => $ok]);
5625 throw new BadRequestException('Error adding activity');
5629 /// @TODO move to top of file or somewhere better
5630 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5631 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5632 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5633 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5634 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5635 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5636 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5637 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5638 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5639 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5642 * @brief Returns notifications
5644 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5647 function api_friendica_notification($type)
5651 if (api_user() === false) {
5652 throw new ForbiddenException();
5655 throw new BadRequestException("Invalid argument count");
5657 $nm = new NotificationsManager();
5659 $notes = $nm->getAll([], "+seen -date", 50);
5661 if ($type == "xml") {
5663 foreach ($notes as $note) {
5664 $xmlnotes[] = ["@attributes" => $note];
5670 return api_format_data("notes", $type, ['note' => $notes]);
5674 * POST request with 'id' param as notification id
5676 * @brief Set notification as seen and returns associated item (if possible)
5678 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5681 function api_friendica_notification_seen($type)
5685 if (api_user() === false) {
5686 throw new ForbiddenException();
5689 throw new BadRequestException("Invalid argument count");
5692 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5694 $nm = new NotificationsManager();
5695 $note = $nm->getByID($id);
5696 if (is_null($note)) {
5697 throw new BadRequestException("Invalid argument");
5700 $nm->setSeen($note);
5701 if ($note['otype']=='item') {
5702 // would be really better with an ItemsManager and $im->getByID() :-P
5704 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5705 intval($note['iid']),
5706 intval(local_user())
5709 // we found the item, return it to the user
5710 $user_info = api_get_user($a);
5711 $ret = api_format_items($r, $user_info, false, $type);
5712 $data = ['status' => $ret];
5713 return api_format_data("status", $type, $data);
5715 // the item can't be found, but we set the note as seen, so we count this as a success
5717 return api_format_data('result', $type, ['result' => "success"]);
5720 /// @TODO move to top of file or somewhere better
5721 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5722 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5725 * @brief update a direct_message to seen state
5727 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5728 * @return string (success result=ok, error result=error with error message)
5730 function api_friendica_direct_messages_setseen($type)
5733 if (api_user() === false) {
5734 throw new ForbiddenException();
5738 $user_info = api_get_user($a);
5739 $uid = $user_info['uid'];
5740 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5742 // return error if id is zero
5744 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5745 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5748 // get data of the specified message id
5750 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5755 // error message if specified id is not in database
5756 if (!DBM::is_result($r)) {
5757 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5758 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5761 // update seen indicator
5763 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5770 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5771 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5773 $answer = ['result' => 'error', 'message' => 'unknown error'];
5774 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5778 /// @TODO move to top of file or somewhere better
5779 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5782 * @brief search for direct_messages containing a searchstring through api
5784 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5785 * @param string $box
5786 * @return string (success: success=true if found and search_result contains found messages,
5787 * success=false if nothing was found, search_result='nothing found',
5788 * error: result=error with error message)
5790 function api_friendica_direct_messages_search($type, $box = "")
5794 if (api_user() === false) {
5795 throw new ForbiddenException();
5799 $user_info = api_get_user($a);
5800 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5801 $uid = $user_info['uid'];
5803 // error if no searchstring specified
5804 if ($searchstring == "") {
5805 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5806 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5809 // get data for the specified searchstring
5811 "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",
5813 dbesc('%'.$searchstring.'%')
5816 $profile_url = $user_info["url"];
5818 // message if nothing was found
5819 if (!DBM::is_result($r)) {
5820 $success = ['success' => false, 'search_results' => 'problem with query'];
5821 } elseif (count($r) == 0) {
5822 $success = ['success' => false, 'search_results' => 'nothing found'];
5825 foreach ($r as $item) {
5826 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5827 $recipient = $user_info;
5828 $sender = api_get_user($a, normalise_link($item['contact-url']));
5829 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5830 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5831 $sender = $user_info;
5834 $ret[] = api_format_messages($item, $recipient, $sender);
5836 $success = ['success' => true, 'search_results' => $ret];
5839 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5842 /// @TODO move to top of file or somewhere better
5843 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5846 * @brief return data of all the profiles a user has to the client
5848 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5851 function api_friendica_profile_show($type)
5855 if (api_user() === false) {
5856 throw new ForbiddenException();
5860 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5862 // retrieve general information about profiles for user
5863 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5864 $directory = Config::get('system', 'directory');
5866 // get data of the specified profile id or all profiles of the user if not specified
5867 if ($profileid != 0) {
5869 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5874 // error message if specified gid is not in database
5875 if (!DBM::is_result($r)) {
5876 throw new BadRequestException("profile_id not available");
5880 "SELECT * FROM `profile` WHERE `uid` = %d",
5884 // loop through all returned profiles and retrieve data and users
5886 foreach ($r as $rr) {
5887 $profile = api_format_items_profiles($rr);
5889 // select all users from contact table, loop and prepare standard return for user data
5892 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5894 intval($rr['profile_id'])
5897 foreach ($r as $rr) {
5898 $user = api_get_user($a, $rr['nurl']);
5899 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5901 $profile['users'] = $users;
5903 // add prepared profile data to array for final return
5904 if ($type == "xml") {
5905 $profiles[$k++ . ":profile"] = $profile;
5907 $profiles[] = $profile;
5911 // return settings, authenticated user and profiles data
5912 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5914 $result = ['multi_profiles' => $multi_profiles ? true : false,
5915 'global_dir' => $directory,
5916 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5917 'profiles' => $profiles];
5918 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5920 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5923 * Returns a list of saved searches.
5925 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5927 * @param string $type Return format: json or xml
5929 * @return string|array
5931 function api_saved_searches_list($type)
5933 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5936 while ($term = $terms->fetch()) {
5938 'created_at' => api_date(time()),
5939 'id' => intval($term['id']),
5940 'id_str' => $term['id'],
5941 'name' => $term['term'],
5943 'query' => $term['term']
5949 return api_format_data("terms", $type, ['terms' => $result]);
5952 /// @TODO move to top of file or somewhere better
5953 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5956 @TODO Maybe open to implement?
5958 [pagename] => api/1.1/statuses/lookup.json
5959 [id] => 605138389168451584
5960 [include_cards] => true
5961 [cards_platform] => Android-12
5962 [include_entities] => true
5963 [include_my_retweet] => 1
5965 [include_reply_count] => true
5966 [include_descendent_reply_count] => true
5970 Not implemented by now:
5971 statuses/retweets_of_me
5976 account/update_location
5977 account/update_profile_background_image
5980 friendica/profile/update
5981 friendica/profile/create
5982 friendica/profile/delete
5984 Not implemented in status.net:
5985 statuses/retweeted_to_me
5986 statuses/retweeted_by_me
5987 direct_messages/destroy
5989 account/update_delivery_device
5990 notifications/follow