3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\Addon;
15 use Friendica\Core\Config;
16 use Friendica\Core\L10n;
17 use Friendica\Core\NotificationsManager;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
21 use Friendica\Database\DBM;
22 use Friendica\Model\Contact;
23 use Friendica\Model\Group;
24 use Friendica\Model\Item;
25 use Friendica\Model\Mail;
26 use Friendica\Model\Photo;
27 use Friendica\Model\User;
28 use Friendica\Network\FKOAuth1;
29 use Friendica\Network\HTTPException;
30 use Friendica\Network\HTTPException\BadRequestException;
31 use Friendica\Network\HTTPException\ForbiddenException;
32 use Friendica\Network\HTTPException\InternalServerErrorException;
33 use Friendica\Network\HTTPException\MethodNotAllowedException;
34 use Friendica\Network\HTTPException\NotFoundException;
35 use Friendica\Network\HTTPException\NotImplementedException;
36 use Friendica\Network\HTTPException\TooManyRequestsException;
37 use Friendica\Network\HTTPException\UnauthorizedException;
38 use Friendica\Object\Image;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Network;
42 use Friendica\Util\XML;
44 require_once 'include/conversation.php';
45 require_once 'mod/share.php';
46 require_once 'mod/item.php';
47 require_once 'include/security.php';
48 require_once 'mod/wall_upload.php';
49 require_once 'mod/proxy.php';
51 define('API_METHOD_ANY', '*');
52 define('API_METHOD_GET', 'GET');
53 define('API_METHOD_POST', 'POST,PUT');
54 define('API_METHOD_DELETE', 'POST,DELETE');
60 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
61 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
62 * into a page, and visitors will post something without noticing it).
64 * @brief Auth API user
68 if (x($_SESSION, 'allow_api')) {
76 * Clients can send 'source' parameter to be show in post metadata
77 * as "sent via <source>".
78 * Some clients doesn't send a source param, we support ones we know
81 * @brief Get source name from API client
84 * Client source name, default to "api" if unset/unknown
88 if (requestdata('source')) {
89 return requestdata('source');
92 // Support for known clients that doesn't send a source name
93 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
97 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
103 * @brief Format date for API
105 * @param string $str Source date, as UTC
106 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
108 function api_date($str)
110 // Wed May 23 06:01:13 +0000 2007
111 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
115 * Register a function to be the endpoint for defined API path.
117 * @brief Register API endpoint
119 * @param string $path API URL path, relative to System::baseUrl()
120 * @param string $func Function name to call on path request
121 * @param bool $auth API need logged user
122 * @param string $method HTTP method reqiured to call this endpoint.
123 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
124 * Default to API_METHOD_ANY
126 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
136 // Workaround for hotot
137 $path = str_replace("api/", "api/1.1/", $path);
147 * Log in user via OAuth1 or Simple HTTP Auth.
148 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
150 * @brief Login API user
152 * @param object $a App
153 * @hook 'authenticate'
155 * 'username' => username from login form
156 * 'password' => password from login form
157 * 'authenticated' => return status,
158 * 'user_record' => return authenticated user record
160 * array $user logged user record
162 function api_login(App $a)
164 $oauth1 = new FKOAuth1();
167 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
168 if (!is_null($token)) {
169 $oauth1->loginUser($token->uid);
170 Addon::callHooks('logged_in', $a->user);
173 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
174 var_dump($consumer, $token);
176 } catch (Exception $e) {
180 // workaround for HTTP-auth in CGI mode
181 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
182 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
183 if (strlen($userpass)) {
184 list($name, $password) = explode(':', $userpass);
185 $_SERVER['PHP_AUTH_USER'] = $name;
186 $_SERVER['PHP_AUTH_PW'] = $password;
190 if (!x($_SERVER, 'PHP_AUTH_USER')) {
191 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
192 header('WWW-Authenticate: Basic realm="Friendica"');
193 throw new UnauthorizedException("This API requires login");
196 $user = $_SERVER['PHP_AUTH_USER'];
197 $password = $_SERVER['PHP_AUTH_PW'];
199 // allow "user@server" login (but ignore 'server' part)
200 $at = strstr($user, "@", true);
205 // next code from mod/auth.php. needs better solution
209 'username' => trim($user),
210 'password' => trim($password),
211 'authenticated' => 0,
212 'user_record' => null,
216 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
217 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
218 * and later addons should not interfere with an earlier one that succeeded.
220 Addon::callHooks('authenticate', $addon_auth);
222 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
223 $record = $addon_auth['user_record'];
225 $user_id = User::authenticate(trim($user), trim($password));
226 if ($user_id !== false) {
227 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
231 if (!DBM::is_result($record)) {
232 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
233 header('WWW-Authenticate: Basic realm="Friendica"');
234 //header('HTTP/1.0 401 Unauthorized');
235 //die('This api requires login');
236 throw new UnauthorizedException("This API requires login");
239 authenticate_success($record);
241 $_SESSION["allow_api"] = true;
243 Addon::callHooks('logged_in', $a->user);
247 * API endpoints can define which HTTP method to accept when called.
248 * This function check the current HTTP method agains endpoint
251 * @brief Check HTTP method of called API
253 * @param string $method Required methods, uppercase, separated by comma
256 function api_check_method($method)
258 if ($method == "*") {
261 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
265 * Authenticate user, call registered API function, set HTTP headers
267 * @brief Main API entry point
269 * @param object $a App
270 * @return string|array API call result
272 function api_call(App $a)
274 global $API, $called_api;
277 if (strpos($a->query_string, ".xml") > 0) {
280 if (strpos($a->query_string, ".json") > 0) {
283 if (strpos($a->query_string, ".rss") > 0) {
286 if (strpos($a->query_string, ".atom") > 0) {
291 foreach ($API as $p => $info) {
292 if (strpos($a->query_string, $p) === 0) {
293 if (!api_check_method($info['method'])) {
294 throw new MethodNotAllowedException();
297 $called_api = explode("/", $p);
298 //unset($_SERVER['PHP_AUTH_USER']);
300 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
301 if ($info['auth'] === true && api_user() === false) {
305 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
306 logger('API parameters: ' . print_r($_REQUEST, true));
308 $stamp = microtime(true);
309 $return = call_user_func($info['func'], $type);
310 $duration = (float) (microtime(true) - $stamp);
311 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
313 if (Config::get("system", "profiler")) {
314 $duration = microtime(true)-$a->performance["start"];
316 /// @TODO round() really everywhere?
318 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
319 "Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
320 round($a->performance["database"] - $a->performance["database_write"], 3),
321 round($a->performance["database_write"], 3),
322 round($a->performance["cache"], 3),
323 round($a->performance["cache_write"], 3),
324 round($a->performance["network"], 2),
325 round($a->performance["file"], 2),
326 round($duration - ($a->performance["database"]
327 + $a->performance["cache"] + $a->performance["cache_write"]
328 + $a->performance["network"] + $a->performance["file"]), 2),
334 if (Config::get("rendertime", "callstack")) {
335 $o = "Database Read:\n";
336 foreach ($a->callstack["database"] as $func => $time) {
337 $time = round($time, 3);
339 $o .= $func . ": " . $time . "\n";
342 $o .= "\nDatabase Write:\n";
343 foreach ($a->callstack["database_write"] as $func => $time) {
344 $time = round($time, 3);
346 $o .= $func . ": " . $time . "\n";
350 $o = "Cache Read:\n";
351 foreach ($a->callstack["cache"] as $func => $time) {
352 $time = round($time, 3);
354 $o .= $func . ": " . $time . "\n";
357 $o .= "\nCache Write:\n";
358 foreach ($a->callstack["cache_write"] as $func => $time) {
359 $time = round($time, 3);
361 $o .= $func . ": " . $time . "\n";
365 $o .= "\nNetwork:\n";
366 foreach ($a->callstack["network"] as $func => $time) {
367 $time = round($time, 3);
369 $o .= $func . ": " . $time . "\n";
372 logger($o, LOGGER_DEBUG);
376 if (false === $return) {
378 * api function returned false withour throw an
379 * exception. This should not happend, throw a 500
381 throw new InternalServerErrorException();
386 header("Content-Type: text/xml");
389 header("Content-Type: application/json");
390 $json = json_encode(end($return));
391 if (x($_GET, 'callback')) {
392 $json = $_GET['callback'] . "(" . $json . ")";
397 header("Content-Type: application/rss+xml");
398 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
401 header("Content-Type: application/atom+xml");
402 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
409 logger('API call not implemented: ' . $a->query_string);
410 throw new NotImplementedException();
411 } catch (HTTPException $e) {
412 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
413 return api_error($type, $e);
418 * @brief Format API error string
420 * @param string $type Return type (xml, json, rss, as)
421 * @param object $e HTTPException Error object
422 * @return string|array error message formatted as $type
424 function api_error($type, $e)
428 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
429 /// @TODO: https://dev.twitter.com/overview/api/response-codes
431 $error = ["error" => $error,
432 "code" => $e->httpcode . " " . $e->httpdesc,
433 "request" => $a->query_string];
435 $return = api_format_data('status', $type, ['status' => $error]);
439 header("Content-Type: text/xml");
442 header("Content-Type: application/json");
443 $return = json_encode($return);
446 header("Content-Type: application/rss+xml");
449 header("Content-Type: application/atom+xml");
457 * @brief Set values for RSS template
460 * @param array $arr Array to be passed to template
461 * @param array $user_info User info
463 * @todo find proper type-hints
465 function api_rss_extra(App $a, $arr, $user_info)
467 if (is_null($user_info)) {
468 $user_info = api_get_user($a);
471 $arr['$user'] = $user_info;
473 'alternate' => $user_info['url'],
474 'self' => System::baseUrl() . "/" . $a->query_string,
475 'base' => System::baseUrl(),
476 'updated' => api_date(null),
477 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
478 'language' => $user_info['language'],
479 'logo' => System::baseUrl() . "/images/friendica-32.png",
487 * @brief Unique contact to contact url.
489 * @param int $id Contact id
490 * @return bool|string
491 * Contact url or False if contact id is unknown
493 function api_unique_id_to_nurl($id)
495 $r = dba::selectFirst('contact', ['nurl'], ['id' => $id]);
497 if (DBM::is_result($r)) {
505 * @brief Get user info array.
507 * @param object $a App
508 * @param int|string $contact_id Contact ID or URL
510 function api_get_user(App $a, $contact_id = null)
518 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
520 // Searching for contact URL
521 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
522 $user = dbesc(normalise_link($contact_id));
524 $extra_query = "AND `contact`.`nurl` = '%s' ";
525 if (api_user() !== false) {
526 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
530 // Searching for contact id with uid = 0
531 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
532 $user = dbesc(api_unique_id_to_nurl(intval($contact_id)));
535 throw new BadRequestException("User ID ".$contact_id." not found.");
539 $extra_query = "AND `contact`.`nurl` = '%s' ";
540 if (api_user() !== false) {
541 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
545 if (is_null($user) && x($_GET, 'user_id')) {
546 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
549 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
553 $extra_query = "AND `contact`.`nurl` = '%s' ";
554 if (api_user() !== false) {
555 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
558 if (is_null($user) && x($_GET, 'screen_name')) {
559 $user = dbesc($_GET['screen_name']);
560 $extra_query = "AND `contact`.`nick` = '%s' ";
561 if (api_user() !== false) {
562 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
566 if (is_null($user) && x($_GET, 'profileurl')) {
567 $user = dbesc(normalise_link($_GET['profileurl']));
568 $extra_query = "AND `contact`.`nurl` = '%s' ";
569 if (api_user() !== false) {
570 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
574 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
575 $argid = count($called_api);
576 list($user, $null) = explode(".", $a->argv[$argid]);
577 if (is_numeric($user)) {
578 $user = dbesc(api_unique_id_to_nurl(intval($user)));
582 $extra_query = "AND `contact`.`nurl` = '%s' ";
583 if (api_user() !== false) {
584 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
588 $user = dbesc($user);
589 $extra_query = "AND `contact`.`nick` = '%s' ";
590 if (api_user() !== false) {
591 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
596 logger("api_get_user: user ".$user, LOGGER_DEBUG);
599 if (api_user() === false) {
603 $user = $_SESSION['uid'];
604 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
608 logger('api_user: ' . $extra_query . ', user: ' . $user);
612 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
618 // Selecting the id by priority, friendica first
619 if (is_array($uinfo)) {
620 api_best_nickname($uinfo);
623 // if the contact wasn't found, fetch it from the contacts with uid = 0
624 if (!DBM::is_result($uinfo)) {
628 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
631 if (DBM::is_result($r)) {
632 $network_name = ContactSelector::networkToName($r[0]['network'], $r[0]['url']);
634 // If no nick where given, extract it from the address
635 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
636 $r[0]['nick'] = api_get_nick($r[0]["url"]);
641 'id_str' => (string) $r[0]["id"],
642 'name' => $r[0]["name"],
643 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
644 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
645 'description' => $r[0]["about"],
646 'profile_image_url' => $r[0]["micro"],
647 'profile_image_url_https' => $r[0]["micro"],
648 'profile_image_url_profile_size' => $r[0]["thumb"],
649 'profile_image_url_large' => $r[0]["photo"],
650 'url' => $r[0]["url"],
651 'protected' => false,
652 'followers_count' => 0,
653 'friends_count' => 0,
655 'created_at' => api_date($r[0]["created"]),
656 'favourites_count' => 0,
658 'time_zone' => 'UTC',
659 'geo_enabled' => false,
661 'statuses_count' => 0,
663 'contributors_enabled' => false,
664 'is_translator' => false,
665 'is_translation_enabled' => false,
666 'following' => false,
667 'follow_request_sent' => false,
668 'statusnet_blocking' => false,
669 'notifications' => false,
670 'statusnet_profile_url' => $r[0]["url"],
672 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
673 'pid' => Contact::getIdForURL($r[0]["url"], 0, true),
675 'network' => $r[0]["network"],
680 throw new BadRequestException("User ".$url." not found.");
684 if ($uinfo[0]['self']) {
685 if ($uinfo[0]['network'] == "") {
686 $uinfo[0]['network'] = NETWORK_DFRN;
689 $usr = dba::selectFirst('user', ['default-location'], ['uid' => api_user()]);
690 $profile = dba::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
692 /// @TODO old-lost code? (twice)
693 // Counting is deactivated by now, due to performance issues
694 // count public wall messages
695 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
696 // intval($uinfo[0]['uid'])
698 //$countitms = $r[0]['count'];
701 // Counting is deactivated by now, due to performance issues
702 //$r = q("SELECT count(*) as `count` FROM `item`
703 // WHERE `contact-id` = %d",
704 // intval($uinfo[0]['id'])
706 //$countitms = $r[0]['count'];
710 /// @TODO old-lost code? (twice)
712 // Counting is deactivated by now, due to performance issues
714 $r = q("SELECT count(*) as `count` FROM `contact`
715 WHERE `uid` = %d AND `rel` IN ( %d, %d )
716 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
717 intval($uinfo[0]['uid']),
718 intval(CONTACT_IS_SHARING),
719 intval(CONTACT_IS_FRIEND)
721 $countfriends = $r[0]['count'];
723 $r = q("SELECT count(*) as `count` FROM `contact`
724 WHERE `uid` = %d AND `rel` IN ( %d, %d )
725 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
726 intval($uinfo[0]['uid']),
727 intval(CONTACT_IS_FOLLOWER),
728 intval(CONTACT_IS_FRIEND)
730 $countfollowers = $r[0]['count'];
732 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
733 intval($uinfo[0]['uid'])
735 $starred = $r[0]['count'];
738 if (! $uinfo[0]['self']) {
748 // Add a nick if it isn't present there
749 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
750 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
753 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
755 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
757 if (!empty($profile['about'])) {
758 $description = $profile['about'];
760 $description = $uinfo[0]["about"];
763 if (!empty($usr['default-location'])) {
764 $location = $usr['default-location'];
765 } elseif (!empty($uinfo[0]["location"])) {
766 $location = $uinfo[0]["location"];
768 $location = $network_name;
772 'id' => intval($pcontact_id),
773 'id_str' => (string) intval($pcontact_id),
774 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
775 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
776 'location' => $location,
777 'description' => $description,
778 'profile_image_url' => $uinfo[0]['micro'],
779 'profile_image_url_https' => $uinfo[0]['micro'],
780 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
781 'profile_image_url_large' => $uinfo[0]["photo"],
782 'url' => $uinfo[0]['url'],
783 'protected' => false,
784 'followers_count' => intval($countfollowers),
785 'friends_count' => intval($countfriends),
787 'created_at' => api_date($uinfo[0]['created']),
788 'favourites_count' => intval($starred),
790 'time_zone' => 'UTC',
791 'geo_enabled' => false,
793 'statuses_count' => intval($countitms),
795 'contributors_enabled' => false,
796 'is_translator' => false,
797 'is_translation_enabled' => false,
798 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
799 'follow_request_sent' => false,
800 'statusnet_blocking' => false,
801 'notifications' => false,
803 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
804 'statusnet_profile_url' => $uinfo[0]['url'],
805 'uid' => intval($uinfo[0]['uid']),
806 'cid' => intval($uinfo[0]['cid']),
807 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
808 'self' => $uinfo[0]['self'],
809 'network' => $uinfo[0]['network'],
812 // If this is a local user and it uses Frio, we can get its color preferences.
814 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
815 if ($theme_info['theme'] === 'frio') {
816 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
817 if ($schema && ($schema != '---')) {
818 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
819 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
820 require_once $schemefile;
823 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
824 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
825 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
831 $link_color = "#6fdbe8";
834 $bgcolor = "#ededed";
837 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
838 $ret['profile_link_color'] = str_replace('#', '', $link_color);
839 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
847 * @brief return api-formatted array for item's author and owner
849 * @param object $a App
850 * @param array $item item from db
851 * @return array(array:author, array:owner)
853 function api_item_get_user(App $a, $item)
855 $status_user = api_get_user($a, $item["author-id"]);
857 $status_user["protected"] = $item["private"];
859 if ($item['thr-parent'] == $item['uri']) {
860 $owner_user = api_get_user($a, $item["owner-id"]);
862 $owner_user = $status_user;
865 return ([$status_user, $owner_user]);
869 * @brief walks recursively through an array with the possibility to change value and key
871 * @param array $array The array to walk through
872 * @param string $callback The callback function
874 * @return array the transformed array
876 function api_walk_recursive(array &$array, callable $callback)
880 foreach ($array as $k => $v) {
882 if ($callback($v, $k)) {
883 $new_array[$k] = api_walk_recursive($v, $callback);
886 if ($callback($v, $k)) {
897 * @brief Callback function to transform the array in an array that can be transformed in a XML file
899 * @param mixed $item Array item value
900 * @param string $key Array key
902 * @return boolean Should the array item be deleted?
904 function api_reformat_xml(&$item, &$key)
906 if (is_bool($item)) {
907 $item = ($item ? "true" : "false");
910 if (substr($key, 0, 10) == "statusnet_") {
911 $key = "statusnet:".substr($key, 10);
912 } elseif (substr($key, 0, 10) == "friendica_") {
913 $key = "friendica:".substr($key, 10);
915 /// @TODO old-lost code?
917 // $key = "default:".$key;
923 * @brief Creates the XML from a JSON style array
925 * @param array $data JSON style array
926 * @param string $root_element Name of the root element
928 * @return string The XML data
930 function api_create_xml(array $data, $root_element)
932 $childname = key($data);
933 $data2 = array_pop($data);
936 $namespaces = ["" => "http://api.twitter.com",
937 "statusnet" => "http://status.net/schema/api/1/",
938 "friendica" => "http://friendi.ca/schema/api/1/",
939 "georss" => "http://www.georss.org/georss"];
941 /// @todo Auto detection of needed namespaces
942 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
946 if (is_array($data2)) {
947 api_walk_recursive($data2, "api_reformat_xml");
954 foreach ($data2 as $item) {
955 $data4[$i++ . ":" . $childname] = $item;
961 $data3 = [$root_element => $data2];
963 $ret = XML::fromArray($data3, $xml, false, $namespaces);
968 * @brief Formats the data according to the data type
970 * @param string $root_element Name of the root element
971 * @param string $type Return type (atom, rss, xml, json)
972 * @param array $data JSON style array
974 * @return (string|array) XML data or JSON data
976 function api_format_data($root_element, $type, $data)
982 $ret = api_create_xml($data, $root_element);
998 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
999 * returns a 401 status code and an error message if not.
1000 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
1002 * @param string $type Return type (atom, rss, xml, json)
1004 function api_account_verify_credentials($type)
1009 if (api_user() === false) {
1010 throw new ForbiddenException();
1013 unset($_REQUEST["user_id"]);
1014 unset($_GET["user_id"]);
1016 unset($_REQUEST["screen_name"]);
1017 unset($_GET["screen_name"]);
1019 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1021 $user_info = api_get_user($a);
1023 // "verified" isn't used here in the standard
1024 unset($user_info["verified"]);
1026 // - Adding last status
1027 if (!$skip_status) {
1028 $user_info["status"] = api_status_show("raw");
1029 if (!count($user_info["status"])) {
1030 unset($user_info["status"]);
1032 unset($user_info["status"]["user"]);
1036 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1037 unset($user_info["uid"]);
1038 unset($user_info["self"]);
1040 return api_format_data("user", $type, ['user' => $user_info]);
1043 /// @TODO move to top of file or somewhere better
1044 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1047 * Get data from $_POST or $_GET
1051 function requestdata($k)
1053 if (x($_POST, $k)) {
1063 * Deprecated function to upload media.
1065 * @param string $type Return type (atom, rss, xml, json)
1067 * @return array|string
1069 function api_statuses_mediap($type)
1073 if (api_user() === false) {
1074 logger('api_statuses_update: no user');
1075 throw new ForbiddenException();
1077 $user_info = api_get_user($a);
1079 $_REQUEST['type'] = 'wall';
1080 $_REQUEST['profile_uid'] = api_user();
1081 $_REQUEST['api_source'] = true;
1082 $txt = requestdata('status');
1083 /// @TODO old-lost code?
1084 //$txt = urldecode(requestdata('status'));
1086 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1087 $txt = html2bb_video($txt);
1088 $config = HTMLPurifier_Config::createDefault();
1089 $config->set('Cache.DefinitionImpl', null);
1090 $purifier = new HTMLPurifier($config);
1091 $txt = $purifier->purify($txt);
1093 $txt = HTML::toBBCode($txt);
1095 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1097 $picture = wall_upload_post($a, false);
1099 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1100 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1103 // this should output the last post (the one we just posted).
1104 return api_status_show($type);
1107 /// @TODO move this to top of file or somewhere better!
1108 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1111 * Updates the user’s current status.
1113 * @param string $type Return type (atom, rss, xml, json)
1115 * @return array|string
1116 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1118 function api_statuses_update($type)
1123 if (api_user() === false) {
1124 logger('api_statuses_update: no user');
1125 throw new ForbiddenException();
1130 // convert $_POST array items to the form we use for web posts.
1131 if (requestdata('htmlstatus')) {
1132 $txt = requestdata('htmlstatus');
1133 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1134 $txt = html2bb_video($txt);
1136 $config = HTMLPurifier_Config::createDefault();
1137 $config->set('Cache.DefinitionImpl', null);
1139 $purifier = new HTMLPurifier($config);
1140 $txt = $purifier->purify($txt);
1142 $_REQUEST['body'] = HTML::toBBCode($txt);
1145 $_REQUEST['body'] = requestdata('status');
1148 $_REQUEST['title'] = requestdata('title');
1150 $parent = requestdata('in_reply_to_status_id');
1152 // Twidere sends "-1" if it is no reply ...
1153 if ($parent == -1) {
1157 if (ctype_digit($parent)) {
1158 $_REQUEST['parent'] = $parent;
1160 $_REQUEST['parent_uri'] = $parent;
1163 if (requestdata('lat') && requestdata('long')) {
1164 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1166 $_REQUEST['profile_uid'] = api_user();
1169 $_REQUEST['type'] = 'net-comment';
1171 // Check for throttling (maximum posts per day, week and month)
1172 $throttle_day = Config::get('system', 'throttle_limit_day');
1173 if ($throttle_day > 0) {
1174 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1177 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1178 AND `created` > '%s' AND `id` = `parent`",
1183 if (DBM::is_result($r)) {
1184 $posts_day = $r[0]["posts_day"];
1189 if ($posts_day > $throttle_day) {
1190 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1191 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1192 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));
1196 $throttle_week = Config::get('system', 'throttle_limit_week');
1197 if ($throttle_week > 0) {
1198 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1201 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1202 AND `created` > '%s' AND `id` = `parent`",
1207 if (DBM::is_result($r)) {
1208 $posts_week = $r[0]["posts_week"];
1213 if ($posts_week > $throttle_week) {
1214 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1215 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1216 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));
1220 $throttle_month = Config::get('system', 'throttle_limit_month');
1221 if ($throttle_month > 0) {
1222 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1225 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1226 AND `created` > '%s' AND `id` = `parent`",
1231 if (DBM::is_result($r)) {
1232 $posts_month = $r[0]["posts_month"];
1237 if ($posts_month > $throttle_month) {
1238 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1239 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1240 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));
1244 $_REQUEST['type'] = 'wall';
1247 if (x($_FILES, 'media')) {
1248 // upload the image if we have one
1249 $picture = wall_upload_post($a, false);
1250 if (is_array($picture)) {
1251 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1255 // To-Do: Multiple IDs
1256 if (requestdata('media_ids')) {
1258 "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",
1259 intval(requestdata('media_ids')),
1262 if (DBM::is_result($r)) {
1263 $phototypes = Image::supportedTypes();
1264 $ext = $phototypes[$r[0]['type']];
1265 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1266 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1270 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1272 $_REQUEST['api_source'] = true;
1274 if (!x($_REQUEST, "source")) {
1275 $_REQUEST["source"] = api_source();
1278 // call out normal post function
1281 // this should output the last post (the one we just posted).
1282 return api_status_show($type);
1285 /// @TODO move to top of file or somewhere better
1286 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1287 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1290 * Uploads an image to Friendica.
1293 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1295 function api_media_upload()
1299 if (api_user() === false) {
1301 throw new ForbiddenException();
1306 if (!x($_FILES, 'media')) {
1308 throw new BadRequestException("No media.");
1311 $media = wall_upload_post($a, false);
1314 throw new InternalServerErrorException();
1318 $returndata["media_id"] = $media["id"];
1319 $returndata["media_id_string"] = (string)$media["id"];
1320 $returndata["size"] = $media["size"];
1321 $returndata["image"] = ["w" => $media["width"],
1322 "h" => $media["height"],
1323 "image_type" => $media["type"]];
1325 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1327 return ["media" => $returndata];
1330 /// @TODO move to top of file or somewhere better
1331 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1335 * @param string $type Return type (atom, rss, xml, json)
1337 * @return array|string
1339 function api_status_show($type)
1343 $user_info = api_get_user($a);
1345 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1347 if ($type == "raw") {
1348 $privacy_sql = "AND NOT `private`";
1353 // get last public wall message
1354 $condition = ["`owner-id` = ? AND `uid` = ? AND `type` != 'activity' ".$privacy_sql,
1355 $user_info['pid'], api_user()];
1356 $lastwall = dba::selectFirst('item', [], $condition, ['order' => ['id' => true]]);
1358 if (DBM::is_result($lastwall)) {
1359 $in_reply_to = api_in_reply_to($lastwall);
1361 $converted = api_convert_item($lastwall);
1363 if ($type == "xml") {
1364 $geo = "georss:point";
1370 'created_at' => api_date($lastwall['created']),
1371 'id' => intval($lastwall['id']),
1372 'id_str' => (string) $lastwall['id'],
1373 'text' => $converted["text"],
1374 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1375 'truncated' => false,
1376 'in_reply_to_status_id' => $in_reply_to['status_id'],
1377 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1378 'in_reply_to_user_id' => $in_reply_to['user_id'],
1379 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1380 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1381 'user' => $user_info,
1383 'coordinates' => "",
1385 'contributors' => "",
1386 'is_quote_status' => false,
1387 'retweet_count' => 0,
1388 'favorite_count' => 0,
1389 'favorited' => $lastwall['starred'] ? true : false,
1390 'retweeted' => false,
1391 'possibly_sensitive' => false,
1393 'statusnet_html' => $converted["html"],
1394 'statusnet_conversation_id' => $lastwall['parent'],
1395 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1398 if (count($converted["attachments"]) > 0) {
1399 $status_info["attachments"] = $converted["attachments"];
1402 if (count($converted["entities"]) > 0) {
1403 $status_info["entities"] = $converted["entities"];
1406 if ($status_info["source"] == 'web') {
1407 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
1408 } elseif (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $status_info["source"]) {
1409 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $user_info['url']).')');
1412 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1413 unset($status_info["user"]["uid"]);
1414 unset($status_info["user"]["self"]);
1416 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1418 if ($type == "raw") {
1419 return $status_info;
1422 return api_format_data("statuses", $type, ['status' => $status_info]);
1427 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1428 * The author's most recent status will be returned inline.
1430 * @param string $type Return type (atom, rss, xml, json)
1431 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1433 function api_users_show($type)
1437 $user_info = api_get_user($a);
1439 $condition = ["`owner-id` = ? AND `uid` = ? AND `verb` = ? AND `type` != 'activity' AND NOT `private`",
1440 $user_info['pid'], api_user(), ACTIVITY_POST];
1441 $lastwall = dba::selectFirst('item', [], $condition, ['order' => ['id' => true]]);
1443 if (DBM::is_result($lastwall)) {
1444 $in_reply_to = api_in_reply_to($lastwall);
1446 $converted = api_convert_item($lastwall);
1448 if ($type == "xml") {
1449 $geo = "georss:point";
1454 $user_info['status'] = [
1455 'text' => $converted["text"],
1456 'truncated' => false,
1457 'created_at' => api_date($lastwall['created']),
1458 'in_reply_to_status_id' => $in_reply_to['status_id'],
1459 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1460 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1461 'id' => intval($lastwall['contact-id']),
1462 'id_str' => (string) $lastwall['contact-id'],
1463 'in_reply_to_user_id' => $in_reply_to['user_id'],
1464 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1465 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1467 'favorited' => $lastwall['starred'] ? true : false,
1468 'statusnet_html' => $converted["html"],
1469 'statusnet_conversation_id' => $lastwall['parent'],
1470 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1473 if (count($converted["attachments"]) > 0) {
1474 $user_info["status"]["attachments"] = $converted["attachments"];
1477 if (count($converted["entities"]) > 0) {
1478 $user_info["status"]["entities"] = $converted["entities"];
1481 if ($user_info["status"]["source"] == 'web') {
1482 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
1485 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1486 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $user_info['url']) . ')');
1490 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1491 unset($user_info["uid"]);
1492 unset($user_info["self"]);
1494 return api_format_data("user", $type, ['user' => $user_info]);
1497 /// @TODO move to top of file or somewhere better
1498 api_register_func('api/users/show', 'api_users_show');
1499 api_register_func('api/externalprofile/show', 'api_users_show');
1502 * Search a public user account.
1504 * @param string $type Return type (atom, rss, xml, json)
1506 * @return array|string
1507 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1509 function api_users_search($type)
1515 if (x($_GET, 'q')) {
1516 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1518 if (!DBM::is_result($r)) {
1519 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1522 if (DBM::is_result($r)) {
1524 foreach ($r as $user) {
1525 $user_info = api_get_user($a, $user["id"]);
1527 if ($type == "xml") {
1528 $userlist[$k++.":user"] = $user_info;
1530 $userlist[] = $user_info;
1533 $userlist = ["users" => $userlist];
1535 throw new BadRequestException("User ".$_GET["q"]." not found.");
1538 throw new BadRequestException("No user specified.");
1541 return api_format_data("users", $type, $userlist);
1544 /// @TODO move to top of file or somewhere better
1545 api_register_func('api/users/search', 'api_users_search');
1548 * Return user objects
1550 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1552 * @param string $type Return format: json or xml
1554 * @return array|string
1555 * @throws NotFoundException if the results are empty.
1557 function api_users_lookup($type)
1561 if (x($_REQUEST['user_id'])) {
1562 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1564 $users[] = api_get_user(get_app(), $id);
1569 if (empty($users)) {
1570 throw new NotFoundException;
1573 return api_format_data("users", $type, ['users' => $users]);
1576 /// @TODO move to top of file or somewhere better
1577 api_register_func('api/users/lookup', 'api_users_lookup', true);
1580 * Returns statuses that match a specified query.
1582 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1584 * @param string $type Return format: json, xml, atom, rss
1586 * @return array|string
1587 * @throws BadRequestException if the "q" parameter is missing.
1589 function api_search($type)
1592 $user_info = api_get_user($a);
1594 if (api_user() === false || $user_info === false) {
1595 throw new ForbiddenException();
1600 if (!x($_REQUEST, 'q')) {
1601 throw new BadRequestException("q parameter is required.");
1604 if (x($_REQUEST, 'rpp')) {
1605 $count = $_REQUEST['rpp'];
1606 } elseif (x($_REQUEST, 'count')) {
1607 $count = $_REQUEST['count'];
1612 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1613 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1614 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1616 $start = $page * $count;
1618 $condition = ["`verb` = ? AND `item`.`id` > ?
1619 AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1620 AND `item`.`body` LIKE CONCAT('%',?,'%')",
1621 ACTIVITY_POST, $since_id, api_user(), $_REQUEST['q']];
1624 $condition[0] .= " AND `item`.`id` <= ?";
1625 $condition[] = $max_id;
1628 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1629 $statuses = Item::select(api_user(), [], $condition, $params);
1631 $data['status'] = api_format_items(dba::inArray($statuses), $user_info);
1633 return api_format_data("statuses", $type, $data);
1636 /// @TODO move to top of file or somewhere better
1637 api_register_func('api/search/tweets', 'api_search', true);
1638 api_register_func('api/search', 'api_search', true);
1641 * Returns the most recent statuses posted by the user and the users they follow.
1643 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1645 * @param string $type Return type (atom, rss, xml, json)
1647 * @todo Optional parameters
1648 * @todo Add reply info
1650 function api_statuses_home_timeline($type)
1653 $user_info = api_get_user($a);
1655 if (api_user() === false || $user_info === false) {
1656 throw new ForbiddenException();
1659 unset($_REQUEST["user_id"]);
1660 unset($_GET["user_id"]);
1662 unset($_REQUEST["screen_name"]);
1663 unset($_GET["screen_name"]);
1665 // get last network messages
1668 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1669 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1673 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1674 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1675 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1676 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1677 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1679 $start = $page * $count;
1681 $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ?", api_user(), ACTIVITY_POST, $since_id];
1684 $condition[0] .= " AND `item`.`id` <= ?";
1685 $condition[] = $max_id;
1687 if ($exclude_replies > 0) {
1688 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1690 if ($conversation_id > 0) {
1691 $condition[0] .= " AND `item`.`parent` = ?";
1692 $condition[] = $conversation_id;
1695 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1696 $statuses = Item::select(api_user(), [], $condition, $params);
1698 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
1700 // Set all posts from the query above to seen
1702 foreach ($r as $item) {
1703 $idarray[] = intval($item["id"]);
1706 if (!empty($idarray)) {
1707 $unseen = dba::exists('item', ['unseen' => true, 'id' => $idarray]);
1709 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1713 $data = ['status' => $ret];
1717 $data = api_rss_extra($a, $data, $user_info);
1721 return api_format_data("statuses", $type, $data);
1724 /// @TODO move to top of file or somewhere better
1725 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1726 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1729 * Returns the most recent statuses from public users.
1731 * @param string $type Return type (atom, rss, xml, json)
1733 * @return array|string
1735 function api_statuses_public_timeline($type)
1738 $user_info = api_get_user($a);
1740 if (api_user() === false || $user_info === false) {
1741 throw new ForbiddenException();
1744 // get last network messages
1747 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1748 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1752 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1753 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1754 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1755 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1756 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1758 $start = $page * $count;
1761 if ($exclude_replies && !$conversation_id) {
1762 $condition = ["`verb` = ? AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1763 ACTIVITY_POST, $since_id];
1766 $condition[0] .= " AND `thread`.`iid` <= ?";
1767 $condition[] = $max_id;
1770 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1771 $statuses = Item::selectThread(api_user(), [], $condition, $params);
1773 $r = dba::inArray($statuses);
1775 $condition = ["`verb` = ? AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1776 ACTIVITY_POST, $since_id];
1779 $condition[0] .= " AND `item`.`id` <= ?";
1780 $condition[] = $max_id;
1782 if ($conversation_id > 0) {
1783 $condition[0] .= " AND `item`.`parent` = ?";
1784 $condition[] = $conversation_id;
1787 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1788 $statuses = Item::select(api_user(), [], $condition, $params);
1790 $r = dba::inArray($statuses);
1793 $ret = api_format_items($r, $user_info, false, $type);
1795 $data = ['status' => $ret];
1799 $data = api_rss_extra($a, $data, $user_info);
1803 return api_format_data("statuses", $type, $data);
1806 /// @TODO move to top of file or somewhere better
1807 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1810 * Returns the most recent statuses posted by users this node knows about.
1812 * @brief Returns the list of public federated posts this node knows about
1814 * @param string $type Return format: json, xml, atom, rss
1815 * @return array|string
1816 * @throws ForbiddenException
1818 function api_statuses_networkpublic_timeline($type)
1821 $user_info = api_get_user($a);
1823 if (api_user() === false || $user_info === false) {
1824 throw new ForbiddenException();
1827 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1828 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1831 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1832 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1836 $start = ($page - 1) * $count;
1838 $condition = ["`uid` = 0 AND `verb` = ? AND `thread`.`iid` > ? AND NOT `private`",
1839 ACTIVITY_POST, $since_id];
1842 $condition[0] .= " AND `thread`.`iid` <= ?";
1843 $condition[] = $max_id;
1846 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1847 $statuses = Item::selectThread(api_user(), [], $condition, $params);
1849 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
1851 $data = ['status' => $ret];
1855 $data = api_rss_extra($a, $data, $user_info);
1859 return api_format_data("statuses", $type, $data);
1862 /// @TODO move to top of file or somewhere better
1863 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1866 * Returns a single status.
1868 * @param string $type Return type (atom, rss, xml, json)
1870 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1872 function api_statuses_show($type)
1875 $user_info = api_get_user($a);
1877 if (api_user() === false || $user_info === false) {
1878 throw new ForbiddenException();
1882 $id = intval($a->argv[3]);
1885 $id = intval($_REQUEST["id"]);
1890 $id = intval($a->argv[4]);
1893 logger('API: api_statuses_show: ' . $id);
1895 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1897 // try to fetch the item for the local user - or the public item, if there is no local one
1898 $uri_item = dba::selectFirst('item', ['uri'], ['id' => $id]);
1899 if (!DBM::is_result($uri_item)) {
1900 throw new BadRequestException("There is no status with this id.");
1903 $item = dba::selectFirst('item', ['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1904 if (!DBM::is_result($item)) {
1905 throw new BadRequestException("There is no status with this id.");
1910 if ($conversation) {
1911 $condition = ['parent' => $id, 'verb' => ACTIVITY_POST];
1912 $params = ['order' => ['id' => true]];
1914 $condition = ['id' => $id, 'verb' => ACTIVITY_POST];
1918 $statuses = Item::select(api_user(), [], $condition, $params);
1920 /// @TODO How about copying this to above methods which don't check $r ?
1921 if (!DBM::is_result($items)) {
1922 throw new BadRequestException("There is no status with this id.");
1925 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
1927 if ($conversation) {
1928 $data = ['status' => $ret];
1929 return api_format_data("statuses", $type, $data);
1931 $data = ['status' => $ret[0]];
1932 return api_format_data("status", $type, $data);
1936 /// @TODO move to top of file or somewhere better
1937 api_register_func('api/statuses/show', 'api_statuses_show', true);
1941 * @param string $type Return type (atom, rss, xml, json)
1943 * @todo nothing to say?
1945 function api_conversation_show($type)
1948 $user_info = api_get_user($a);
1950 if (api_user() === false || $user_info === false) {
1951 throw new ForbiddenException();
1955 $id = intval($a->argv[3]);
1956 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1957 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1961 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1962 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1964 $start = $page*$count;
1967 $id = intval($_REQUEST["id"]);
1972 $id = intval($a->argv[4]);
1975 logger('API: api_conversation_show: '.$id);
1977 // try to fetch the item for the local user - or the public item, if there is no local one
1978 $item = dba::selectFirst('item', ['parent-uri'], ['id' => $id]);
1979 if (!DBM::is_result($item)) {
1980 throw new BadRequestException("There is no status with this id.");
1983 $parent = dba::selectFirst('item', ['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1984 if (!DBM::is_result($parent)) {
1985 throw new BadRequestException("There is no status with this id.");
1988 $id = $parent['id'];
1990 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `verb` = ? AND `item`.`id` > ?",
1991 $id, api_user(), ACTIVITY_POST, $since_id];
1994 $condition[0] .= " AND `item`.`id` <= ?";
1995 $condition[] = $max_id;
1998 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1999 $statuses = Item::select(api_user(), [], $condition, $params);
2001 if (!DBM::is_result($items)) {
2002 throw new BadRequestException("There is no status with id $id.");
2005 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
2007 $data = ['status' => $ret];
2008 return api_format_data("statuses", $type, $data);
2011 /// @TODO move to top of file or somewhere better
2012 api_register_func('api/conversation/show', 'api_conversation_show', true);
2013 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2018 * @param string $type Return type (atom, rss, xml, json)
2020 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2022 function api_statuses_repeat($type)
2028 if (api_user() === false) {
2029 throw new ForbiddenException();
2035 $id = intval($a->argv[3]);
2038 $id = intval($_REQUEST["id"]);
2043 $id = intval($a->argv[4]);
2046 logger('API: api_statuses_repeat: '.$id);
2048 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2049 $item = Item::selectFirst(api_user(), $fields, ['id' => $id, 'private' => false]);
2051 if (DBM::is_result($item) && $item['body'] != "") {
2052 if (strpos($item['body'], "[/share]") !== false) {
2053 $pos = strpos($item['body'], "[share");
2054 $post = substr($item['body'], $pos);
2056 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2058 $post .= $item['body'];
2059 $post .= "[/share]";
2061 $_REQUEST['body'] = $post;
2062 $_REQUEST['profile_uid'] = api_user();
2063 $_REQUEST['type'] = 'wall';
2064 $_REQUEST['api_source'] = true;
2066 if (!x($_REQUEST, "source")) {
2067 $_REQUEST["source"] = api_source();
2072 throw new ForbiddenException();
2075 // this should output the last post (the one we just posted).
2077 return api_status_show($type);
2080 /// @TODO move to top of file or somewhere better
2081 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2084 * Destroys a specific status.
2086 * @param string $type Return type (atom, rss, xml, json)
2088 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2090 function api_statuses_destroy($type)
2094 if (api_user() === false) {
2095 throw new ForbiddenException();
2101 $id = intval($a->argv[3]);
2104 $id = intval($_REQUEST["id"]);
2109 $id = intval($a->argv[4]);
2112 logger('API: api_statuses_destroy: '.$id);
2114 $ret = api_statuses_show($type);
2116 Item::deleteForUser(['id' => $id], api_user());
2121 /// @TODO move to top of file or somewhere better
2122 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2125 * Returns the most recent mentions.
2127 * @param string $type Return type (atom, rss, xml, json)
2129 * @see http://developer.twitter.com/doc/get/statuses/mentions
2131 function api_statuses_mentions($type)
2134 $user_info = api_get_user($a);
2136 if (api_user() === false || $user_info === false) {
2137 throw new ForbiddenException();
2140 unset($_REQUEST["user_id"]);
2141 unset($_GET["user_id"]);
2143 unset($_REQUEST["screen_name"]);
2144 unset($_GET["screen_name"]);
2146 // get last network messages
2149 $since_id = defaults($_REQUEST, 'since_id', 0);
2150 $max_id = defaults($_REQUEST, 'max_id' , 0);
2151 $count = defaults($_REQUEST, 'count' , 20);
2152 $page = defaults($_REQUEST, 'page' , 1);
2157 $start = ($page - 1) * $count;
2159 $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ? AND `author-id` != ?
2160 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = ? AND `mention` AND NOT `ignored`)",
2161 api_user(), ACTIVITY_POST, $since_id, $user_info['pid'], api_user()];
2164 $condition[0] .= " AND `item`.`id` <= ?";
2165 $condition[] = $max_id;
2168 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2169 $statuses = Item::select(api_user(), [], $condition, $params);
2171 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
2173 $data = ['status' => $ret];
2177 $data = api_rss_extra($a, $data, $user_info);
2181 return api_format_data("statuses", $type, $data);
2184 /// @TODO move to top of file or somewhere better
2185 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2186 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2189 * Returns the most recent statuses posted by the user.
2191 * @brief Returns a user's public timeline
2193 * @param string $type Either "json" or "xml"
2194 * @return string|array
2195 * @throws ForbiddenException
2196 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2198 function api_statuses_user_timeline($type)
2201 $user_info = api_get_user($a);
2203 if (api_user() === false || $user_info === false) {
2204 throw new ForbiddenException();
2208 "api_statuses_user_timeline: api_user: ". api_user() .
2209 "\nuser_info: ".print_r($user_info, true) .
2210 "\n_REQUEST: ".print_r($_REQUEST, true),
2214 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2215 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2216 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2217 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2220 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2221 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2225 $start = ($page - 1) * $count;
2227 $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2228 api_user(), ACTIVITY_POST, $since_id, $user_info['cid']];
2230 if ($user_info['self'] == 1) {
2231 $condition[0] .= ' AND `item`.`wall` ';
2234 if ($exclude_replies > 0) {
2235 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2238 if ($conversation_id > 0) {
2239 $condition[0] .= " AND `item`.`parent` = ?";
2240 $condition[] = $conversation_id;
2244 $condition[0] .= " AND `item`.`id` <= ?";
2245 $condition[] = $max_id;
2248 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2249 $statuses = Item::select(api_user(), [], $condition, $params);
2251 $ret = api_format_items(dba::inArray($statuses), $user_info, true, $type);
2253 $data = ['status' => $ret];
2257 $data = api_rss_extra($a, $data, $user_info);
2261 return api_format_data("statuses", $type, $data);
2264 /// @TODO move to top of file or somewhere better
2265 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2268 * Star/unstar an item.
2269 * param: id : id of the item
2271 * @param string $type Return type (atom, rss, xml, json)
2273 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2275 function api_favorites_create_destroy($type)
2279 if (api_user() === false) {
2280 throw new ForbiddenException();
2283 // for versioned api.
2284 /// @TODO We need a better global soluton
2285 $action_argv_id = 2;
2286 if ($a->argv[1] == "1.1") {
2287 $action_argv_id = 3;
2290 if ($a->argc <= $action_argv_id) {
2291 throw new BadRequestException("Invalid request.");
2293 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2294 if ($a->argc == $action_argv_id + 2) {
2295 $itemid = intval($a->argv[$action_argv_id + 1]);
2297 /// @TODO use x() to check if _REQUEST contains 'id'
2298 $itemid = intval($_REQUEST['id']);
2301 $item = Item::selectFirst(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2303 if (!DBM::is_result($item)) {
2304 throw new BadRequestException("Invalid item.");
2309 $item['starred'] = 1;
2312 $item['starred'] = 0;
2315 throw new BadRequestException("Invalid action ".$action);
2318 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2321 throw new InternalServerErrorException("DB error");
2325 $user_info = api_get_user($a);
2326 $rets = api_format_items([$item], $user_info, false, $type);
2329 $data = ['status' => $ret];
2333 $data = api_rss_extra($a, $data, $user_info);
2336 return api_format_data("status", $type, $data);
2339 /// @TODO move to top of file or somewhere better
2340 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2341 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2344 * Returns the most recent favorite statuses.
2346 * @param string $type Return type (atom, rss, xml, json)
2348 * @return string|array
2350 function api_favorites($type)
2355 $user_info = api_get_user($a);
2357 if (api_user() === false || $user_info === false) {
2358 throw new ForbiddenException();
2363 // in friendica starred item are private
2364 // return favorites only for self
2365 logger('api_favorites: self:' . $user_info['self']);
2367 if ($user_info['self'] == 0) {
2371 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2372 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2373 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2374 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2379 $start = $page*$count;
2381 $condition = ["`uid` = ? AND `verb` = ? AND `id` > ? AND `starred`",
2382 api_user(), ACTIVITY_POST, $since_id];
2384 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2387 $condition[0] .= " AND `item`.`id` <= ?";
2388 $condition[] = $max_id;
2391 $statuses = Item::select(api_user(), [], $condition, $params);
2393 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
2396 $data = ['status' => $ret];
2400 $data = api_rss_extra($a, $data, $user_info);
2403 return api_format_data("statuses", $type, $data);
2406 /// @TODO move to top of file or somewhere better
2407 api_register_func('api/favorites', 'api_favorites', true);
2411 * @param array $item
2412 * @param array $recipient
2413 * @param array $sender
2417 function api_format_messages($item, $recipient, $sender)
2419 // standard meta information
2421 'id' => $item['id'],
2422 'sender_id' => $sender['id'] ,
2424 'recipient_id' => $recipient['id'],
2425 'created_at' => api_date($item['created']),
2426 'sender_screen_name' => $sender['screen_name'],
2427 'recipient_screen_name' => $recipient['screen_name'],
2428 'sender' => $sender,
2429 'recipient' => $recipient,
2431 'friendica_seen' => $item['seen'],
2432 'friendica_parent_uri' => $item['parent-uri'],
2435 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2436 unset($ret["sender"]["uid"]);
2437 unset($ret["sender"]["self"]);
2438 unset($ret["recipient"]["uid"]);
2439 unset($ret["recipient"]["self"]);
2441 //don't send title to regular StatusNET requests to avoid confusing these apps
2442 if (x($_GET, 'getText')) {
2443 $ret['title'] = $item['title'];
2444 if ($_GET['getText'] == 'html') {
2445 $ret['text'] = BBCode::convert($item['body'], false);
2446 } elseif ($_GET['getText'] == 'plain') {
2447 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2450 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2452 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2453 unset($ret['sender']);
2454 unset($ret['recipient']);
2462 * @param array $item
2466 function api_convert_item($item)
2468 $body = $item['body'];
2469 $attachments = api_get_attachments($body);
2471 // Workaround for ostatus messages where the title is identically to the body
2472 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2473 $statusbody = trim(HTML::toPlaintext($html, 0));
2475 // handle data: images
2476 $statusbody = api_format_items_embeded_images($item, $statusbody);
2478 $statustitle = trim($item['title']);
2480 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2481 $statustext = trim($statusbody);
2483 $statustext = trim($statustitle."\n\n".$statusbody);
2486 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2487 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2490 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2492 // Workaround for clients with limited HTML parser functionality
2493 $search = ["<br>", "<blockquote>", "</blockquote>",
2494 "<h1>", "</h1>", "<h2>", "</h2>",
2495 "<h3>", "</h3>", "<h4>", "</h4>",
2496 "<h5>", "</h5>", "<h6>", "</h6>"];
2497 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2498 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2499 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2500 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2501 $statushtml = str_replace($search, $replace, $statushtml);
2503 if ($item['title'] != "") {
2504 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2508 $oldtext = $statushtml;
2509 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2510 } while ($oldtext != $statushtml);
2512 if (substr($statushtml, 0, 4) == '<br>') {
2513 $statushtml = substr($statushtml, 4);
2516 if (substr($statushtml, 0, -4) == '<br>') {
2517 $statushtml = substr($statushtml, -4);
2520 // feeds without body should contain the link
2521 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2522 $statushtml .= BBCode::convert($item['plink']);
2525 $entities = api_get_entitities($statustext, $body);
2528 "text" => $statustext,
2529 "html" => $statushtml,
2530 "attachments" => $attachments,
2531 "entities" => $entities
2537 * @param string $body
2541 function api_get_attachments(&$body)
2544 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2546 $URLSearchString = "^\[\]";
2547 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2555 foreach ($images[1] as $image) {
2556 $imagedata = Image::getInfoFromURL($image);
2559 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2563 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2564 foreach ($images[0] as $orig) {
2565 $body = str_replace($orig, "", $body);
2569 return $attachments;
2574 * @param string $text
2575 * @param string $bbcode
2578 * @todo Links at the first character of the post
2580 function api_get_entitities(&$text, $bbcode)
2582 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2584 if ($include_entities != "true") {
2585 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2587 foreach ($images[1] as $image) {
2588 $replace = proxy_url($image);
2589 $text = str_replace($image, $replace, $text);
2594 $bbcode = BBCode::cleanPictureLinks($bbcode);
2596 // Change pure links in text to bbcode uris
2597 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2600 $entities["hashtags"] = [];
2601 $entities["symbols"] = [];
2602 $entities["urls"] = [];
2603 $entities["user_mentions"] = [];
2605 $URLSearchString = "^\[\]";
2607 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2609 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2610 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2611 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2613 $bbcode = preg_replace(
2614 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2615 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2618 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2620 $bbcode = preg_replace(
2621 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2622 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2625 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2627 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2629 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2630 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2633 foreach ($urls[1] as $id => $url) {
2634 //$start = strpos($text, $url, $offset);
2635 $start = iconv_strpos($text, $url, 0, "UTF-8");
2636 if (!($start === false)) {
2637 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2641 ksort($ordered_urls);
2644 //foreach ($urls[1] AS $id=>$url) {
2645 foreach ($ordered_urls as $url) {
2646 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2647 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2649 $display_url = $url["title"];
2651 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2652 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2654 if (strlen($display_url) > 26) {
2655 $display_url = substr($display_url, 0, 25)."…";
2659 //$start = strpos($text, $url, $offset);
2660 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2661 if (!($start === false)) {
2662 $entities["urls"][] = ["url" => $url["url"],
2663 "expanded_url" => $url["url"],
2664 "display_url" => $display_url,
2665 "indices" => [$start, $start+strlen($url["url"])]];
2666 $offset = $start + 1;
2670 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2671 $ordered_images = [];
2672 foreach ($images[1] as $image) {
2673 //$start = strpos($text, $url, $offset);
2674 $start = iconv_strpos($text, $image, 0, "UTF-8");
2675 if (!($start === false)) {
2676 $ordered_images[$start] = $image;
2679 //$entities["media"] = array();
2682 foreach ($ordered_images as $url) {
2683 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2684 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2686 if (strlen($display_url) > 26) {
2687 $display_url = substr($display_url, 0, 25)."…";
2690 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2691 if (!($start === false)) {
2692 $image = Image::getInfoFromURL($url);
2694 // If image cache is activated, then use the following sizes:
2695 // thumb (150), small (340), medium (600) and large (1024)
2696 if (!Config::get("system", "proxy_disabled")) {
2697 $media_url = proxy_url($url);
2700 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2701 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2703 if (($image[0] > 150) || ($image[1] > 150)) {
2704 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2705 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2708 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2709 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2711 if (($image[0] > 600) || ($image[1] > 600)) {
2712 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2713 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2717 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2720 $entities["media"][] = [
2722 "id_str" => (string)$start+1,
2723 "indices" => [$start, $start+strlen($url)],
2724 "media_url" => normalise_link($media_url),
2725 "media_url_https" => $media_url,
2727 "display_url" => $display_url,
2728 "expanded_url" => $url,
2732 $offset = $start + 1;
2741 * @param array $item
2742 * @param string $text
2746 function api_format_items_embeded_images($item, $text)
2748 $text = preg_replace_callback(
2749 '|data:image/([^;]+)[^=]+=*|m',
2750 function () use ($item) {
2751 return System::baseUrl() . '/display/' . $item['guid'];
2759 * @brief return <a href='url'>name</a> as array
2761 * @param string $txt text
2766 function api_contactlink_to_array($txt)
2769 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2770 if ($r && count($match)==3) {
2772 'name' => $match[2],
2786 * @brief return likes, dislikes and attend status for item
2788 * @param array $item array
2789 * @param string $type Return type (atom, rss, xml, json)
2792 * likes => int count,
2793 * dislikes => int count
2795 function api_format_items_activities(&$item, $type = "json")
2804 'attendmaybe' => [],
2808 'SELECT * FROM `item`
2809 WHERE `uid` = %d AND `thr-parent` = "%s" AND `visible` AND NOT `deleted`',
2810 intval($item['uid']),
2814 foreach ($items as $i) {
2815 // not used as result should be structured like other user data
2816 //builtin_activity_puller($i, $activities);
2818 // get user data and add it to the array of the activity
2819 $user = api_get_user($a, $i['author-id']);
2820 switch ($i['verb']) {
2822 $activities['like'][] = $user;
2824 case ACTIVITY_DISLIKE:
2825 $activities['dislike'][] = $user;
2827 case ACTIVITY_ATTEND:
2828 $activities['attendyes'][] = $user;
2830 case ACTIVITY_ATTENDNO:
2831 $activities['attendno'][] = $user;
2833 case ACTIVITY_ATTENDMAYBE:
2834 $activities['attendmaybe'][] = $user;
2841 if ($type == "xml") {
2842 $xml_activities = [];
2843 foreach ($activities as $k => $v) {
2844 // change xml element from "like" to "friendica:like"
2845 $xml_activities["friendica:".$k] = $v;
2846 // add user data into xml output
2848 foreach ($v as $user) {
2849 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2852 $activities = $xml_activities;
2860 * @brief return data from profiles
2862 * @param array $profile_row array containing data from db table 'profile'
2865 function api_format_items_profiles($profile_row)
2868 'profile_id' => $profile_row['id'],
2869 'profile_name' => $profile_row['profile-name'],
2870 'is_default' => $profile_row['is-default'] ? true : false,
2871 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2872 'profile_photo' => $profile_row['photo'],
2873 'profile_thumb' => $profile_row['thumb'],
2874 'publish' => $profile_row['publish'] ? true : false,
2875 'net_publish' => $profile_row['net-publish'] ? true : false,
2876 'description' => $profile_row['pdesc'],
2877 'date_of_birth' => $profile_row['dob'],
2878 'address' => $profile_row['address'],
2879 'city' => $profile_row['locality'],
2880 'region' => $profile_row['region'],
2881 'postal_code' => $profile_row['postal-code'],
2882 'country' => $profile_row['country-name'],
2883 'hometown' => $profile_row['hometown'],
2884 'gender' => $profile_row['gender'],
2885 'marital' => $profile_row['marital'],
2886 'marital_with' => $profile_row['with'],
2887 'marital_since' => $profile_row['howlong'],
2888 'sexual' => $profile_row['sexual'],
2889 'politic' => $profile_row['politic'],
2890 'religion' => $profile_row['religion'],
2891 'public_keywords' => $profile_row['pub_keywords'],
2892 'private_keywords' => $profile_row['prv_keywords'],
2893 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2894 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2895 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2896 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2897 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2898 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2899 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2900 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2901 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2902 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2903 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2904 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2905 'homepage' => $profile_row['homepage'],
2912 * @brief format items to be returned by api
2914 * @param array $r array of items
2915 * @param array $user_info
2916 * @param bool $filter_user filter items by $user_info
2917 * @param string $type Return type (atom, rss, xml, json)
2919 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2925 foreach ($r as $item) {
2926 localize_item($item);
2927 list($status_user, $owner_user) = api_item_get_user($a, $item);
2929 // Look if the posts are matching if they should be filtered by user id
2930 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2934 $in_reply_to = api_in_reply_to($item);
2936 $converted = api_convert_item($item);
2938 if ($type == "xml") {
2939 $geo = "georss:point";
2945 'text' => $converted["text"],
2946 'truncated' => false,
2947 'created_at'=> api_date($item['created']),
2948 'in_reply_to_status_id' => $in_reply_to['status_id'],
2949 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2950 'source' => (($item['app']) ? $item['app'] : 'web'),
2951 'id' => intval($item['id']),
2952 'id_str' => (string) intval($item['id']),
2953 'in_reply_to_user_id' => $in_reply_to['user_id'],
2954 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2955 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2957 'favorited' => $item['starred'] ? true : false,
2958 'user' => $status_user ,
2959 'friendica_owner' => $owner_user,
2960 //'entities' => NULL,
2961 'statusnet_html' => $converted["html"],
2962 'statusnet_conversation_id' => $item['parent'],
2963 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2964 'friendica_activities' => api_format_items_activities($item, $type),
2967 if (count($converted["attachments"]) > 0) {
2968 $status["attachments"] = $converted["attachments"];
2971 if (count($converted["entities"]) > 0) {
2972 $status["entities"] = $converted["entities"];
2975 if ($status["source"] == 'web') {
2976 $status["source"] = ContactSelector::networkToName($item['network'], $user_info['url']);
2977 } elseif (ContactSelector::networkToName($item['network'], $user_info['url']) != $status["source"]) {
2978 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $user_info['url']).')');
2981 if ($item["id"] == $item["parent"]) {
2982 $retweeted_item = api_share_as_retweet($item);
2983 if ($retweeted_item !== false) {
2984 $retweeted_status = $status;
2986 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
2987 } catch (BadRequestException $e) {
2988 // user not found. should be found?
2989 /// @todo check if the user should be always found
2990 $retweeted_status["user"] = [];
2993 $rt_converted = api_convert_item($retweeted_item);
2995 $retweeted_status['text'] = $rt_converted["text"];
2996 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2997 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2998 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2999 $status['retweeted_status'] = $retweeted_status;
3003 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3004 unset($status["user"]["uid"]);
3005 unset($status["user"]["self"]);
3007 if ($item["coord"] != "") {
3008 $coords = explode(' ', $item["coord"]);
3009 if (count($coords) == 2) {
3010 if ($type == "json") {
3011 $status["geo"] = ['type' => 'Point',
3012 'coordinates' => [(float) $coords[0],
3013 (float) $coords[1]]];
3014 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3015 $status["georss:point"] = $item["coord"];
3025 * Returns the remaining number of API requests available to the user before the API limit is reached.
3027 * @param string $type Return type (atom, rss, xml, json)
3029 * @return array|string
3031 function api_account_rate_limit_status($type)
3033 if ($type == "xml") {
3035 'remaining-hits' => '150',
3036 '@attributes' => ["type" => "integer"],
3037 'hourly-limit' => '150',
3038 '@attributes2' => ["type" => "integer"],
3039 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3040 '@attributes3' => ["type" => "datetime"],
3041 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3042 '@attributes4' => ["type" => "integer"],
3046 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3047 'remaining_hits' => '150',
3048 'hourly_limit' => '150',
3049 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3053 return api_format_data('hash', $type, ['hash' => $hash]);
3056 /// @TODO move to top of file or somewhere better
3057 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3060 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3062 * @param string $type Return type (atom, rss, xml, json)
3064 * @return array|string
3066 function api_help_test($type)
3068 if ($type == 'xml') {
3074 return api_format_data('ok', $type, ["ok" => $ok]);
3077 /// @TODO move to top of file or somewhere better
3078 api_register_func('api/help/test', 'api_help_test', false);
3081 * Returns all lists the user subscribes to.
3083 * @param string $type Return type (atom, rss, xml, json)
3085 * @return array|string
3086 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3088 function api_lists_list($type)
3091 /// @TODO $ret is not filled here?
3092 return api_format_data('lists', $type, ["lists_list" => $ret]);
3095 /// @TODO move to top of file or somewhere better
3096 api_register_func('api/lists/list', 'api_lists_list', true);
3097 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3100 * Returns all groups the user owns.
3102 * @param string $type Return type (atom, rss, xml, json)
3104 * @return array|string
3105 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3107 function api_lists_ownerships($type)
3111 if (api_user() === false) {
3112 throw new ForbiddenException();
3116 $user_info = api_get_user($a);
3117 $uid = $user_info['uid'];
3119 $groups = dba::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3121 // loop through all groups
3123 foreach ($groups as $group) {
3124 if ($group['visible']) {
3130 'name' => $group['name'],
3131 'id' => intval($group['id']),
3132 'id_str' => (string) $group['id'],
3133 'user' => $user_info,
3137 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3140 /// @TODO move to top of file or somewhere better
3141 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3144 * Returns recent statuses from users in the specified group.
3146 * @param string $type Return type (atom, rss, xml, json)
3148 * @return array|string
3149 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3151 function api_lists_statuses($type)
3155 $user_info = api_get_user($a);
3156 if (api_user() === false || $user_info === false) {
3157 throw new ForbiddenException();
3160 unset($_REQUEST["user_id"]);
3161 unset($_GET["user_id"]);
3163 unset($_REQUEST["screen_name"]);
3164 unset($_GET["screen_name"]);
3166 if (empty($_REQUEST['list_id'])) {
3167 throw new BadRequestException('list_id not specified');
3171 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
3172 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
3176 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3177 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3178 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
3179 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
3181 $start = $page * $count;
3183 $condition = ["`uid` = ? AND `verb` = ? AND `id` > ? AND `group_member`.`gid` = ?",
3184 api_user(), ACTIVITY_POST, $since_id, $_REQUEST['list_id']];
3187 $condition[0] .= " AND `item`.`id` <= ?";
3188 $condition[] = $max_id;
3190 if ($exclude_replies > 0) {
3191 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3193 if ($conversation_id > 0) {
3194 $condition[0] .= " AND `item`.`parent` = ?";
3195 $condition[] = $conversation_id;
3198 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3199 $statuses = Item::select(api_user(), [], $condition, $params);
3201 $items = api_format_items(dba::inArray($statuses), $user_info, false, $type);
3203 $data = ['status' => $items];
3207 $data = api_rss_extra($a, $data, $user_info);
3211 return api_format_data("statuses", $type, $data);
3214 /// @TODO move to top of file or somewhere better
3215 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3218 * Considers friends and followers lists to be private and won't return
3219 * anything if any user_id parameter is passed.
3221 * @brief Returns either the friends of the follower list
3223 * @param string $qtype Either "friends" or "followers"
3224 * @return boolean|array
3225 * @throws ForbiddenException
3227 function api_statuses_f($qtype)
3231 if (api_user() === false) {
3232 throw new ForbiddenException();
3236 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3237 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3241 $start = ($page - 1) * $count;
3243 $user_info = api_get_user($a);
3245 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3246 /* this is to stop Hotot to load friends multiple times
3247 * I'm not sure if I'm missing return something or
3248 * is a bug in hotot. Workaround, meantime
3252 return array('$users' => $ret);*/
3257 if ($qtype == 'friends') {
3258 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3259 } elseif ($qtype == 'followers') {
3260 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3263 // friends and followers only for self
3264 if ($user_info['self'] == 0) {
3265 $sql_extra = " AND false ";
3268 if ($qtype == 'blocks') {
3269 $sql_filter = 'AND `blocked` AND NOT `pending`';
3270 } elseif ($qtype == 'incoming') {
3271 $sql_filter = 'AND `pending`';
3273 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3291 foreach ($r as $cid) {
3292 $user = api_get_user($a, $cid['nurl']);
3293 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3294 unset($user["uid"]);
3295 unset($user["self"]);
3302 return ['user' => $ret];
3307 * Returns the user's friends.
3309 * @brief Returns the list of friends of the provided user
3311 * @deprecated By Twitter API in favor of friends/list
3313 * @param string $type Either "json" or "xml"
3314 * @return boolean|string|array
3316 function api_statuses_friends($type)
3318 $data = api_statuses_f("friends");
3319 if ($data === false) {
3322 return api_format_data("users", $type, $data);
3326 * Returns the user's followers.
3328 * @brief Returns the list of followers of the provided user
3330 * @deprecated By Twitter API in favor of friends/list
3332 * @param string $type Either "json" or "xml"
3333 * @return boolean|string|array
3335 function api_statuses_followers($type)
3337 $data = api_statuses_f("followers");
3338 if ($data === false) {
3341 return api_format_data("users", $type, $data);
3344 /// @TODO move to top of file or somewhere better
3345 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3346 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3349 * Returns the list of blocked users
3351 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3353 * @param string $type Either "json" or "xml"
3355 * @return boolean|string|array
3357 function api_blocks_list($type)
3359 $data = api_statuses_f('blocks');
3360 if ($data === false) {
3363 return api_format_data("users", $type, $data);
3366 /// @TODO move to top of file or somewhere better
3367 api_register_func('api/blocks/list', 'api_blocks_list', true);
3370 * Returns the list of pending users IDs
3372 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3374 * @param string $type Either "json" or "xml"
3376 * @return boolean|string|array
3378 function api_friendships_incoming($type)
3380 $data = api_statuses_f('incoming');
3381 if ($data === false) {
3386 foreach ($data['user'] as $user) {
3387 $ids[] = $user['id'];
3390 return api_format_data("ids", $type, ['id' => $ids]);
3393 /// @TODO move to top of file or somewhere better
3394 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3397 * Returns the instance's configuration information.
3399 * @param string $type Return type (atom, rss, xml, json)
3401 * @return array|string
3403 function api_statusnet_config($type)
3407 $name = $a->config['sitename'];
3408 $server = $a->get_hostname();
3409 $logo = System::baseUrl() . '/images/friendica-64.png';
3410 $email = $a->config['admin_email'];
3411 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3412 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3413 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3414 if ($a->config['api_import_size']) {
3415 $textlimit = (string) $a->config['api_import_size'];
3417 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3418 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3421 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3422 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3423 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3424 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3425 'shorturllength' => '30',
3427 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3428 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3429 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3430 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3435 return api_format_data('config', $type, ['config' => $config]);
3438 /// @TODO move to top of file or somewhere better
3439 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3440 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3444 * @param string $type Return type (atom, rss, xml, json)
3446 * @return array|string
3448 function api_statusnet_version($type)
3451 $fake_statusnet_version = "0.9.7";
3453 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3456 /// @TODO move to top of file or somewhere better
3457 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3458 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3462 * @param string $type Return type (atom, rss, xml, json)
3464 * @todo use api_format_data() to return data
3466 function api_ff_ids($type)
3469 throw new ForbiddenException();
3476 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3479 "SELECT `pcontact`.`id` FROM `contact`
3480 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3481 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3484 if (!DBM::is_result($r)) {
3489 foreach ($r as $rr) {
3490 if ($stringify_ids) {
3493 $ids[] = intval($rr['id']);
3497 return api_format_data("ids", $type, ['id' => $ids]);
3501 * Returns the ID of every user the user is following.
3503 * @param string $type Return type (atom, rss, xml, json)
3505 * @return array|string
3506 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3508 function api_friends_ids($type)
3510 return api_ff_ids($type);
3514 * Returns the ID of every user following the user.
3516 * @param string $type Return type (atom, rss, xml, json)
3518 * @return array|string
3519 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3521 function api_followers_ids($type)
3523 return api_ff_ids($type);
3526 /// @TODO move to top of file or somewhere better
3527 api_register_func('api/friends/ids', 'api_friends_ids', true);
3528 api_register_func('api/followers/ids', 'api_followers_ids', true);
3531 * Sends a new direct message.
3533 * @param string $type Return type (atom, rss, xml, json)
3535 * @return array|string
3536 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3538 function api_direct_messages_new($type)
3543 if (api_user() === false) {
3544 throw new ForbiddenException();
3547 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3551 $sender = api_get_user($a);
3553 if ($_POST['screen_name']) {
3555 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3557 dbesc($_POST['screen_name'])
3560 // Selecting the id by priority, friendica first
3561 api_best_nickname($r);
3563 $recipient = api_get_user($a, $r[0]['nurl']);
3565 $recipient = api_get_user($a, $_POST['user_id']);
3570 if (x($_REQUEST, 'replyto')) {
3572 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3574 intval($_REQUEST['replyto'])
3576 $replyto = $r[0]['parent-uri'];
3577 $sub = $r[0]['title'];
3579 if (x($_REQUEST, 'title')) {
3580 $sub = $_REQUEST['title'];
3582 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3586 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3589 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3590 $ret = api_format_messages($r[0], $recipient, $sender);
3592 $ret = ["error"=>$id];
3595 $data = ['direct_message'=>$ret];
3600 $data = api_rss_extra($a, $data, $sender);
3603 return api_format_data("direct-messages", $type, $data);
3606 /// @TODO move to top of file or somewhere better
3607 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3610 * Destroys a direct message.
3612 * @brief delete a direct_message from mail table through api
3614 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3615 * @return string|array
3616 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3618 function api_direct_messages_destroy($type)
3622 if (api_user() === false) {
3623 throw new ForbiddenException();
3627 $user_info = api_get_user($a);
3629 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3631 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3632 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3633 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3635 $uid = $user_info['uid'];
3636 // error if no id or parenturi specified (for clients posting parent-uri as well)
3637 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3638 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3639 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3642 // BadRequestException if no id specified (for clients using Twitter API)
3644 throw new BadRequestException('Message id not specified');
3647 // add parent-uri to sql command if specified by calling app
3648 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3650 // get data of the specified message id
3652 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3657 // error message if specified id is not in database
3658 if (!DBM::is_result($r)) {
3659 if ($verbose == "true") {
3660 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3661 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3663 /// @todo BadRequestException ok for Twitter API clients?
3664 throw new BadRequestException('message id not in database');
3669 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3674 if ($verbose == "true") {
3677 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3678 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3680 $answer = ['result' => 'error', 'message' => 'unknown error'];
3681 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3684 /// @todo return JSON data like Twitter API not yet implemented
3687 /// @TODO move to top of file or somewhere better
3688 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3692 * @param string $type Return type (atom, rss, xml, json)
3693 * @param string $box
3694 * @param string $verbose
3696 * @return array|string
3698 function api_direct_messages_box($type, $box, $verbose)
3701 $user_info = api_get_user($a);
3703 if (api_user() === false || $user_info === false) {
3704 throw new ForbiddenException();
3708 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3709 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3714 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3715 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3717 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3718 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3721 unset($_REQUEST["user_id"]);
3722 unset($_GET["user_id"]);
3724 unset($_REQUEST["screen_name"]);
3725 unset($_GET["screen_name"]);
3727 $profile_url = $user_info["url"];
3730 $start = $page * $count;
3735 if ($box=="sentbox") {
3736 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3737 } elseif ($box == "conversation") {
3738 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3739 } elseif ($box == "all") {
3740 $sql_extra = "true";
3741 } elseif ($box == "inbox") {
3742 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3746 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3749 if ($user_id != "") {
3750 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3751 } elseif ($screen_name !="") {
3752 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3756 "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",
3762 if ($verbose == "true" && !DBM::is_result($r)) {
3763 $answer = ['result' => 'error', 'message' => 'no mails available'];
3764 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3768 foreach ($r as $item) {
3769 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3770 $recipient = $user_info;
3771 $sender = api_get_user($a, normalise_link($item['contact-url']));
3772 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3773 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3774 $sender = $user_info;
3777 if (isset($recipient) && isset($sender)) {
3778 $ret[] = api_format_messages($item, $recipient, $sender);
3783 $data = ['direct_message' => $ret];
3787 $data = api_rss_extra($a, $data, $user_info);
3790 return api_format_data("direct-messages", $type, $data);
3794 * Returns the most recent direct messages sent by the user.
3796 * @param string $type Return type (atom, rss, xml, json)
3798 * @return array|string
3799 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3801 function api_direct_messages_sentbox($type)
3803 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3804 return api_direct_messages_box($type, "sentbox", $verbose);
3808 * Returns the most recent direct messages sent to the user.
3810 * @param string $type Return type (atom, rss, xml, json)
3812 * @return array|string
3813 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3815 function api_direct_messages_inbox($type)
3817 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3818 return api_direct_messages_box($type, "inbox", $verbose);
3823 * @param string $type Return type (atom, rss, xml, json)
3825 * @return array|string
3827 function api_direct_messages_all($type)
3829 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3830 return api_direct_messages_box($type, "all", $verbose);
3835 * @param string $type Return type (atom, rss, xml, json)
3837 * @return array|string
3839 function api_direct_messages_conversation($type)
3841 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3842 return api_direct_messages_box($type, "conversation", $verbose);
3845 /// @TODO move to top of file or somewhere better
3846 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3847 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3848 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3849 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3852 * Returns an OAuth Request Token.
3854 * @see https://oauth.net/core/1.0/#auth_step1
3856 function api_oauth_request_token()
3858 $oauth1 = new FKOAuth1();
3860 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3861 } catch (Exception $e) {
3862 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3870 * Returns an OAuth Access Token.
3872 * @return array|string
3873 * @see https://oauth.net/core/1.0/#auth_step3
3875 function api_oauth_access_token()
3877 $oauth1 = new FKOAuth1();
3879 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3880 } catch (Exception $e) {
3881 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3888 /// @TODO move to top of file or somewhere better
3889 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3890 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3894 * @brief delete a complete photoalbum with all containing photos from database through api
3896 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3897 * @return string|array
3899 function api_fr_photoalbum_delete($type)
3901 if (api_user() === false) {
3902 throw new ForbiddenException();
3905 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3907 // we do not allow calls without album string
3909 throw new BadRequestException("no albumname specified");
3911 // check if album is existing
3913 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3917 if (!DBM::is_result($r)) {
3918 throw new BadRequestException("album not available");
3921 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3922 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3923 foreach ($r as $rr) {
3925 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3926 intval(local_user()),
3927 dbesc($rr['resource-id'])
3930 if (!DBM::is_result($photo_item)) {
3931 throw new InternalServerErrorException("problem with deleting items occured");
3933 Item::deleteForUser(['id' => $photo_item[0]['id']], api_user());
3936 // now let's delete all photos from the album
3937 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
3939 // return success of deletion or error message
3941 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
3942 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
3944 throw new InternalServerErrorException("unknown error - deleting from database failed");
3949 * @brief update the name of the album for all photos of an album
3951 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3952 * @return string|array
3954 function api_fr_photoalbum_update($type)
3956 if (api_user() === false) {
3957 throw new ForbiddenException();
3960 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3961 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3963 // we do not allow calls without album string
3965 throw new BadRequestException("no albumname specified");
3967 if ($album_new == "") {
3968 throw new BadRequestException("no new albumname specified");
3970 // check if album is existing
3971 if (!dba::exists('photo', ['uid' => api_user(), 'album' => $album])) {
3972 throw new BadRequestException("album not available");
3974 // now let's update all photos to the albumname
3975 $result = dba::update('photo', ['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
3977 // return success of updating or error message
3979 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
3980 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
3982 throw new InternalServerErrorException("unknown error - updating in database failed");
3988 * @brief list all photos of the authenticated user
3990 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3991 * @return string|array
3993 function api_fr_photos_list($type)
3995 if (api_user() === false) {
3996 throw new ForbiddenException();
3999 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4000 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4001 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4002 intval(local_user())
4005 'image/jpeg' => 'jpg',
4006 'image/png' => 'png',
4007 'image/gif' => 'gif'
4009 $data = ['photo'=>[]];
4010 if (DBM::is_result($r)) {
4011 foreach ($r as $rr) {
4013 $photo['id'] = $rr['resource-id'];
4014 $photo['album'] = $rr['album'];
4015 $photo['filename'] = $rr['filename'];
4016 $photo['type'] = $rr['type'];
4017 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4018 $photo['created'] = $rr['created'];
4019 $photo['edited'] = $rr['edited'];
4020 $photo['desc'] = $rr['desc'];
4022 if ($type == "xml") {
4023 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4025 $photo['thumb'] = $thumb;
4026 $data['photo'][] = $photo;
4030 return api_format_data("photos", $type, $data);
4034 * @brief upload a new photo or change an existing photo
4036 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4037 * @return string|array
4039 function api_fr_photo_create_update($type)
4041 if (api_user() === false) {
4042 throw new ForbiddenException();
4045 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4046 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4047 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4048 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4049 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4050 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4051 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4052 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4053 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4055 // do several checks on input parameters
4056 // we do not allow calls without album string
4057 if ($album == null) {
4058 throw new BadRequestException("no albumname specified");
4060 // if photo_id == null --> we are uploading a new photo
4061 if ($photo_id == null) {
4064 // error if no media posted in create-mode
4065 if (!x($_FILES, 'media')) {
4067 throw new BadRequestException("no media data submitted");
4070 // album_new will be ignored in create-mode
4075 // check if photo is existing in database
4077 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4082 if (!DBM::is_result($r)) {
4083 throw new BadRequestException("photo not available");
4087 // checks on acl strings provided by clients
4088 $acl_input_error = false;
4089 $acl_input_error |= check_acl_input($allow_cid);
4090 $acl_input_error |= check_acl_input($deny_cid);
4091 $acl_input_error |= check_acl_input($allow_gid);
4092 $acl_input_error |= check_acl_input($deny_gid);
4093 if ($acl_input_error) {
4094 throw new BadRequestException("acl data invalid");
4096 // now let's upload the new media in create-mode
4097 if ($mode == "create") {
4098 $media = $_FILES['media'];
4099 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4101 // return success of updating or error message
4102 if (!is_null($data)) {
4103 return api_format_data("photo_create", $type, $data);
4105 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4109 // now let's do the changes in update-mode
4110 if ($mode == "update") {
4113 if (!is_null($desc)) {
4114 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4117 if (!is_null($album_new)) {
4118 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4121 if (!is_null($allow_cid)) {
4122 $allow_cid = trim($allow_cid);
4123 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4126 if (!is_null($deny_cid)) {
4127 $deny_cid = trim($deny_cid);
4128 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4131 if (!is_null($allow_gid)) {
4132 $allow_gid = trim($allow_gid);
4133 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4136 if (!is_null($deny_gid)) {
4137 $deny_gid = trim($deny_gid);
4138 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4142 if ($sql_extra != "") {
4143 $nothingtodo = false;
4145 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4147 DateTimeFormat::utcNow(), // update edited timestamp
4153 $nothingtodo = true;
4156 if (x($_FILES, 'media')) {
4157 $nothingtodo = false;
4158 $media = $_FILES['media'];
4159 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4160 if (!is_null($data)) {
4161 return api_format_data("photo_update", $type, $data);
4165 // return success of updating or error message
4167 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4168 return api_format_data("photo_update", $type, ['$result' => $answer]);
4171 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4172 return api_format_data("photo_update", $type, ['$result' => $answer]);
4174 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4177 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4181 * @brief delete a single photo from the database through api
4183 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4184 * @return string|array
4186 function api_fr_photo_delete($type)
4188 if (api_user() === false) {
4189 throw new ForbiddenException();
4192 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4194 // do several checks on input parameters
4195 // we do not allow calls without photo id
4196 if ($photo_id == null) {
4197 throw new BadRequestException("no photo_id specified");
4199 // check if photo is existing in database
4201 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4205 if (!DBM::is_result($r)) {
4206 throw new BadRequestException("photo not available");
4208 // now we can perform on the deletion of the photo
4209 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4211 // return success of deletion or error message
4213 // retrieve the id of the parent element (the photo element)
4215 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4216 intval(local_user()),
4220 if (!DBM::is_result($photo_item)) {
4221 throw new InternalServerErrorException("problem with deleting items occured");
4223 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4224 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4225 Item::deleteForUser(['id' => $photo_item[0]['id']], api_user());
4227 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4228 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4230 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4236 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4238 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4239 * @return string|array
4241 function api_fr_photo_detail($type)
4243 if (api_user() === false) {
4244 throw new ForbiddenException();
4246 if (!x($_REQUEST, 'photo_id')) {
4247 throw new BadRequestException("No photo id.");
4250 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4251 $photo_id = $_REQUEST['photo_id'];
4253 // prepare json/xml output with data from database for the requested photo
4254 $data = prepare_photo_data($type, $scale, $photo_id);
4256 return api_format_data("photo_detail", $type, $data);
4261 * Updates the user’s profile image.
4263 * @brief updates the profile image for the user (either a specified profile or the default profile)
4265 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4267 * @return string|array
4268 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4270 function api_account_update_profile_image($type)
4272 if (api_user() === false) {
4273 throw new ForbiddenException();
4276 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4278 // error if image data is missing
4279 if (!x($_FILES, 'image')) {
4280 throw new BadRequestException("no media data submitted");
4283 // check if specified profile id is valid
4284 if ($profile_id != 0) {
4285 $profile = dba::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4286 // error message if specified profile id is not in database
4287 if (!DBM::is_result($profile)) {
4288 throw new BadRequestException("profile_id not available");
4290 $is_default_profile = $profile['is-default'];
4292 $is_default_profile = 1;
4295 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4297 if (x($_FILES, 'image')) {
4298 $media = $_FILES['image'];
4299 } elseif (x($_FILES, 'media')) {
4300 $media = $_FILES['media'];
4302 // save new profile image
4303 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4306 if (is_array($media['type'])) {
4307 $filetype = $media['type'][0];
4309 $filetype = $media['type'];
4311 if ($filetype == "image/jpeg") {
4313 } elseif ($filetype == "image/png") {
4316 throw new InternalServerErrorException('Unsupported filetype');
4319 // change specified profile or all profiles to the new resource-id
4320 if ($is_default_profile) {
4321 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4322 dba::update('photo', ['profile' => false], $condition);
4324 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4325 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4326 dba::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4329 Contact::updateSelfFromUserID(api_user(), true);
4331 // Update global directory in background
4332 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4333 if ($url && strlen(Config::get('system', 'directory'))) {
4334 Worker::add(PRIORITY_LOW, "Directory", $url);
4337 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4339 // output for client
4341 return api_account_verify_credentials($type);
4343 // SaveMediaToDatabase failed for some reason
4344 throw new InternalServerErrorException("image upload failed");
4348 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4349 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4350 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4351 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4352 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4353 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4354 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4355 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4356 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4359 * Update user profile
4361 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4363 * @return array|string
4365 function api_account_update_profile($type)
4367 $local_user = api_user();
4368 $api_user = api_get_user(get_app());
4370 if (!empty($_POST['name'])) {
4371 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4372 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4373 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4374 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4377 if (isset($_POST['description'])) {
4378 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4379 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4380 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4383 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4384 // Update global directory in background
4385 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4386 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4389 return api_account_verify_credentials($type);
4392 /// @TODO move to top of file or somewhere better
4393 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4397 * @param string $acl_string
4399 function check_acl_input($acl_string)
4401 if ($acl_string == null || $acl_string == " ") {
4404 $contact_not_found = false;
4406 // split <x><y><z> into array of cid's
4407 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4409 // check for each cid if it is available on server
4410 $cid_array = $array[0];
4411 foreach ($cid_array as $cid) {
4412 $cid = str_replace("<", "", $cid);
4413 $cid = str_replace(">", "", $cid);
4415 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4419 $contact_not_found |= !DBM::is_result($contact);
4421 return $contact_not_found;
4426 * @param string $mediatype
4427 * @param array $media
4428 * @param string $type
4429 * @param string $album
4430 * @param string $allow_cid
4431 * @param string $deny_cid
4432 * @param string $allow_gid
4433 * @param string $deny_gid
4434 * @param string $desc
4435 * @param integer $profile
4436 * @param boolean $visibility
4437 * @param string $photo_id
4439 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)
4447 if (is_array($media)) {
4448 if (is_array($media['tmp_name'])) {
4449 $src = $media['tmp_name'][0];
4451 $src = $media['tmp_name'];
4453 if (is_array($media['name'])) {
4454 $filename = basename($media['name'][0]);
4456 $filename = basename($media['name']);
4458 if (is_array($media['size'])) {
4459 $filesize = intval($media['size'][0]);
4461 $filesize = intval($media['size']);
4463 if (is_array($media['type'])) {
4464 $filetype = $media['type'][0];
4466 $filetype = $media['type'];
4470 if ($filetype == "") {
4471 $filetype=Image::guessType($filename);
4473 $imagedata = getimagesize($src);
4475 $filetype = $imagedata['mime'];
4478 "File upload src: " . $src . " - filename: " . $filename .
4479 " - size: " . $filesize . " - type: " . $filetype,
4483 // check if there was a php upload error
4484 if ($filesize == 0 && $media['error'] == 1) {
4485 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4487 // check against max upload size within Friendica instance
4488 $maximagesize = Config::get('system', 'maximagesize');
4489 if ($maximagesize && ($filesize > $maximagesize)) {
4490 $formattedBytes = formatBytes($maximagesize);
4491 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4494 // create Photo instance with the data of the image
4495 $imagedata = @file_get_contents($src);
4496 $Image = new Image($imagedata, $filetype);
4497 if (! $Image->isValid()) {
4498 throw new InternalServerErrorException("unable to process image data");
4501 // check orientation of image
4502 $Image->orient($src);
4505 // check max length of images on server
4506 $max_length = Config::get('system', 'max_image_length');
4507 if (! $max_length) {
4508 $max_length = MAX_IMAGE_LENGTH;
4510 if ($max_length > 0) {
4511 $Image->scaleDown($max_length);
4512 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4514 $width = $Image->getWidth();
4515 $height = $Image->getHeight();
4517 // create a new resource-id if not already provided
4518 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4520 if ($mediatype == "photo") {
4521 // upload normal image (scales 0, 1, 2)
4522 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4524 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4526 logger("photo upload: image upload with scale 0 (original size) failed");
4528 if ($width > 640 || $height > 640) {
4529 $Image->scaleDown(640);
4530 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4532 logger("photo upload: image upload with scale 1 (640x640) failed");
4536 if ($width > 320 || $height > 320) {
4537 $Image->scaleDown(320);
4538 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4540 logger("photo upload: image upload with scale 2 (320x320) failed");
4543 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4544 } elseif ($mediatype == "profileimage") {
4545 // upload profile image (scales 4, 5, 6)
4546 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4548 if ($width > 175 || $height > 175) {
4549 $Image->scaleDown(175);
4550 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4552 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4556 if ($width > 80 || $height > 80) {
4557 $Image->scaleDown(80);
4558 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4560 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4564 if ($width > 48 || $height > 48) {
4565 $Image->scaleDown(48);
4566 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4568 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4571 $Image->__destruct();
4572 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4575 if (isset($r) && $r) {
4576 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4577 if ($photo_id == null && $mediatype == "photo") {
4578 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4580 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4581 return prepare_photo_data($type, false, $hash);
4583 throw new InternalServerErrorException("image upload failed");
4589 * @param string $hash
4590 * @param string $allow_cid
4591 * @param string $deny_cid
4592 * @param string $allow_gid
4593 * @param string $deny_gid
4594 * @param string $filetype
4595 * @param boolean $visibility
4597 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4599 // get data about the api authenticated user
4600 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4601 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4604 $arr['guid'] = get_guid(32);
4605 $arr['uid'] = intval(api_user());
4607 $arr['parent-uri'] = $uri;
4608 $arr['type'] = 'photo';
4610 $arr['resource-id'] = $hash;
4611 $arr['contact-id'] = $owner_record[0]['id'];
4612 $arr['owner-name'] = $owner_record[0]['name'];
4613 $arr['owner-link'] = $owner_record[0]['url'];
4614 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4615 $arr['author-name'] = $owner_record[0]['name'];
4616 $arr['author-link'] = $owner_record[0]['url'];
4617 $arr['author-avatar'] = $owner_record[0]['thumb'];
4619 $arr['allow_cid'] = $allow_cid;
4620 $arr['allow_gid'] = $allow_gid;
4621 $arr['deny_cid'] = $deny_cid;
4622 $arr['deny_gid'] = $deny_gid;
4623 $arr['visible'] = $visibility;
4627 'image/jpeg' => 'jpg',
4628 'image/png' => 'png',
4629 'image/gif' => 'gif'
4632 // adds link to the thumbnail scale photo
4633 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4634 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4637 // do the magic for storing the item in the database and trigger the federation to other contacts
4643 * @param string $type
4645 * @param string $photo_id
4649 function prepare_photo_data($type, $scale, $photo_id)
4652 $user_info = api_get_user($a);
4654 if ($user_info === false) {
4655 throw new ForbiddenException();
4658 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4659 $data_sql = ($scale === false ? "" : "data, ");
4661 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4662 // clients needs to convert this in their way for further processing
4664 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4665 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4666 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4667 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4669 intval(local_user()),
4675 'image/jpeg' => 'jpg',
4676 'image/png' => 'png',
4677 'image/gif' => 'gif'
4680 // prepare output data for photo
4681 if (DBM::is_result($r)) {
4682 $data = ['photo' => $r[0]];
4683 $data['photo']['id'] = $data['photo']['resource-id'];
4684 if ($scale !== false) {
4685 $data['photo']['data'] = base64_encode($data['photo']['data']);
4687 unset($data['photo']['datasize']); //needed only with scale param
4689 if ($type == "xml") {
4690 $data['photo']['links'] = [];
4691 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4692 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4694 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4697 $data['photo']['link'] = [];
4698 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4700 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4701 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4705 unset($data['photo']['resource-id']);
4706 unset($data['photo']['minscale']);
4707 unset($data['photo']['maxscale']);
4709 throw new NotFoundException();
4712 // retrieve item element for getting activities (like, dislike etc.) related to photo
4714 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4715 intval(local_user()),
4718 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4720 // retrieve comments on photo
4721 $condition = ["`parent` = ? AND `uid` = ? AND (`verb` = ? OR `type`='photo')",
4722 $item[0]['parent'], api_user(), ACTIVITY_POST];
4724 $statuses = Item::select(api_user(), [], $condition);
4726 // prepare output of comments
4727 $commentData = api_format_items(dba::inArray($statuses), $user_info, false, $type);
4729 if ($type == "xml") {
4731 foreach ($commentData as $comment) {
4732 $comments[$k++ . ":comment"] = $comment;
4735 foreach ($commentData as $comment) {
4736 $comments[] = $comment;
4739 $data['photo']['friendica_comments'] = $comments;
4741 // include info if rights on photo and rights on item are mismatching
4742 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4743 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4744 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4745 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4746 $data['photo']['rights_mismatch'] = $rights_mismatch;
4753 * Similar as /mod/redir.php
4754 * redirect to 'url' after dfrn auth
4756 * Why this when there is mod/redir.php already?
4757 * This use api_user() and api_login()
4760 * c_url: url of remote contact to auth to
4761 * url: string, url to redirect after auth
4763 function api_friendica_remoteauth()
4765 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4766 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4768 if ($url === '' || $c_url === '') {
4769 throw new BadRequestException("Wrong parameters.");
4772 $c_url = normalise_link($c_url);
4776 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4778 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4779 throw new BadRequestException("Unknown contact");
4782 $cid = $contact['id'];
4784 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4786 if ($contact['duplex'] && $contact['issued-id']) {
4787 $orig_id = $contact['issued-id'];
4788 $dfrn_id = '1:' . $orig_id;
4790 if ($contact['duplex'] && $contact['dfrn-id']) {
4791 $orig_id = $contact['dfrn-id'];
4792 $dfrn_id = '0:' . $orig_id;
4795 $sec = random_string();
4797 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4798 'sec' => $sec, 'expire' => time() + 45];
4799 dba::insert('profile_check', $fields);
4801 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4802 $dest = ($url ? '&destination_url=' . $url : '');
4804 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4805 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4806 . '&type=profile&sec=' . $sec . $dest
4809 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4812 * @brief Return the item shared, if the item contains only the [share] tag
4814 * @param array $item Sharer item
4815 * @return array|false Shared item or false if not a reshare
4817 function api_share_as_retweet(&$item)
4819 $body = trim($item["body"]);
4821 if (Diaspora::isReshare($body, false)===false) {
4825 /// @TODO "$1" should maybe mean '$1' ?
4826 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4828 * Skip if there is no shared message in there
4829 * we already checked this in diaspora::isReshare()
4830 * but better one more than one less...
4832 if ($body == $attributes) {
4837 // build the fake reshared item
4838 $reshared_item = $item;
4841 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4842 if ($matches[1] != "") {
4843 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4846 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4847 if ($matches[1] != "") {
4848 $author = $matches[1];
4852 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4853 if ($matches[1] != "") {
4854 $profile = $matches[1];
4857 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4858 if ($matches[1] != "") {
4859 $profile = $matches[1];
4863 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4864 if ($matches[1] != "") {
4865 $avatar = $matches[1];
4868 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4869 if ($matches[1] != "") {
4870 $avatar = $matches[1];
4874 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4875 if ($matches[1] != "") {
4876 $link = $matches[1];
4879 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4880 if ($matches[1] != "") {
4881 $link = $matches[1];
4885 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4886 if ($matches[1] != "") {
4887 $posted = $matches[1];
4890 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4891 if ($matches[1] != "") {
4892 $posted = $matches[1];
4895 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4897 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4901 $reshared_item["body"] = $shared_body;
4902 $reshared_item["author-name"] = $author;
4903 $reshared_item["author-link"] = $profile;
4904 $reshared_item["author-avatar"] = $avatar;
4905 $reshared_item["plink"] = $link;
4906 $reshared_item["created"] = $posted;
4907 $reshared_item["edited"] = $posted;
4909 return $reshared_item;
4914 * @param string $profile
4916 * @return string|false
4917 * @todo remove trailing junk from profile url
4918 * @todo pump.io check has to check the website
4920 function api_get_nick($profile)
4925 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4926 dbesc(normalise_link($profile))
4929 if (DBM::is_result($r)) {
4930 $nick = $r[0]["nick"];
4935 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4936 dbesc(normalise_link($profile))
4939 if (DBM::is_result($r)) {
4940 $nick = $r[0]["nick"];
4945 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4946 if ($friendica != $profile) {
4952 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4953 if ($diaspora != $profile) {
4959 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4960 if ($twitter != $profile) {
4967 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4968 if ($StatusnetHost != $profile) {
4969 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4970 if ($StatusnetUser != $profile) {
4971 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4972 $user = json_decode($UserData);
4974 $nick = $user->screen_name;
4980 // To-Do: look at the page if its really a pumpio site
4981 //if (!$nick == "") {
4982 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4983 // if ($pumpio != $profile)
4985 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4998 * @param array $item
5002 function api_in_reply_to($item)
5006 $in_reply_to['status_id'] = null;
5007 $in_reply_to['user_id'] = null;
5008 $in_reply_to['status_id_str'] = null;
5009 $in_reply_to['user_id_str'] = null;
5010 $in_reply_to['screen_name'] = null;
5012 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5014 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5015 intval($item['uid']),
5016 dbesc($item['thr-parent'])
5019 if (DBM::is_result($r)) {
5020 $in_reply_to['status_id'] = intval($r[0]['id']);
5022 $in_reply_to['status_id'] = intval($item['parent']);
5025 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5028 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM `item`
5029 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5030 WHERE `item`.`id` = %d LIMIT 1",
5031 intval($in_reply_to['status_id'])
5034 if (DBM::is_result($r)) {
5035 if ($r[0]['nick'] == "") {
5036 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5039 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5040 $in_reply_to['user_id'] = intval($r[0]['id']);
5041 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5044 // There seems to be situation, where both fields are identical:
5045 // https://github.com/friendica/friendica/issues/1010
5046 // This is a bugfix for that.
5047 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5048 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5049 $in_reply_to['status_id'] = null;
5050 $in_reply_to['user_id'] = null;
5051 $in_reply_to['status_id_str'] = null;
5052 $in_reply_to['user_id_str'] = null;
5053 $in_reply_to['screen_name'] = null;
5057 return $in_reply_to;
5062 * @param string $text
5066 function api_clean_plain_items($text)
5068 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5070 $text = BBCode::cleanPictureLinks($text);
5071 $URLSearchString = "^\[\]";
5073 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5075 if ($include_entities == "true") {
5076 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5079 // Simplify "attachment" element
5080 $text = api_clean_attachments($text);
5086 * @brief Removes most sharing information for API text export
5088 * @param string $body The original body
5090 * @return string Cleaned body
5092 function api_clean_attachments($body)
5094 $data = BBCode::getAttachmentData($body);
5101 if (isset($data["text"])) {
5102 $body = $data["text"];
5104 if (($body == "") && isset($data["title"])) {
5105 $body = $data["title"];
5107 if (isset($data["url"])) {
5108 $body .= "\n".$data["url"];
5110 $body .= $data["after"];
5117 * @param array $contacts
5121 function api_best_nickname(&$contacts)
5125 if (count($contacts) == 0) {
5129 foreach ($contacts as $contact) {
5130 if ($contact["network"] == "") {
5131 $contact["network"] = "dfrn";
5132 $best_contact = [$contact];
5136 if (sizeof($best_contact) == 0) {
5137 foreach ($contacts as $contact) {
5138 if ($contact["network"] == "dfrn") {
5139 $best_contact = [$contact];
5144 if (sizeof($best_contact) == 0) {
5145 foreach ($contacts as $contact) {
5146 if ($contact["network"] == "dspr") {
5147 $best_contact = [$contact];
5152 if (sizeof($best_contact) == 0) {
5153 foreach ($contacts as $contact) {
5154 if ($contact["network"] == "stat") {
5155 $best_contact = [$contact];
5160 if (sizeof($best_contact) == 0) {
5161 foreach ($contacts as $contact) {
5162 if ($contact["network"] == "pump") {
5163 $best_contact = [$contact];
5168 if (sizeof($best_contact) == 0) {
5169 foreach ($contacts as $contact) {
5170 if ($contact["network"] == "twit") {
5171 $best_contact = [$contact];
5176 if (sizeof($best_contact) == 1) {
5177 $contacts = $best_contact;
5179 $contacts = [$contacts[0]];
5184 * Return all or a specified group of the user with the containing contacts.
5186 * @param string $type Return type (atom, rss, xml, json)
5188 * @return array|string
5190 function api_friendica_group_show($type)
5194 if (api_user() === false) {
5195 throw new ForbiddenException();
5199 $user_info = api_get_user($a);
5200 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5201 $uid = $user_info['uid'];
5203 // get data of the specified group id or all groups if not specified
5206 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5210 // error message if specified gid is not in database
5211 if (!DBM::is_result($r)) {
5212 throw new BadRequestException("gid not available");
5216 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5221 // loop through all groups and retrieve all members for adding data in the user array
5223 foreach ($r as $rr) {
5224 $members = Contact::getByGroupId($rr['id']);
5227 if ($type == "xml") {
5228 $user_element = "users";
5230 foreach ($members as $member) {
5231 $user = api_get_user($a, $member['nurl']);
5232 $users[$k++.":user"] = $user;
5235 $user_element = "user";
5236 foreach ($members as $member) {
5237 $user = api_get_user($a, $member['nurl']);
5241 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5243 return api_format_data("groups", $type, ['group' => $grps]);
5245 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5249 * Delete the specified group of the user.
5251 * @param string $type Return type (atom, rss, xml, json)
5253 * @return array|string
5255 function api_friendica_group_delete($type)
5259 if (api_user() === false) {
5260 throw new ForbiddenException();
5264 $user_info = api_get_user($a);
5265 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5266 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5267 $uid = $user_info['uid'];
5269 // error if no gid specified
5270 if ($gid == 0 || $name == "") {
5271 throw new BadRequestException('gid or name not specified');
5274 // get data of the specified group id
5276 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5280 // error message if specified gid is not in database
5281 if (!DBM::is_result($r)) {
5282 throw new BadRequestException('gid not available');
5285 // get data of the specified group id and group name
5287 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5292 // error message if specified gid is not in database
5293 if (!DBM::is_result($rname)) {
5294 throw new BadRequestException('wrong group name');
5298 $ret = Group::removeByName($uid, $name);
5301 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5302 return api_format_data("group_delete", $type, ['result' => $success]);
5304 throw new BadRequestException('other API error');
5307 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5312 * @param string $type Return type (atom, rss, xml, json)
5314 * @return array|string
5315 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5317 function api_lists_destroy($type)
5321 if (api_user() === false) {
5322 throw new ForbiddenException();
5326 $user_info = api_get_user($a);
5327 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5328 $uid = $user_info['uid'];
5330 // error if no gid specified
5332 throw new BadRequestException('gid not specified');
5335 // get data of the specified group id
5336 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5337 // error message if specified gid is not in database
5339 throw new BadRequestException('gid not available');
5342 if (Group::remove($gid)) {
5344 'name' => $group['name'],
5345 'id' => intval($gid),
5346 'id_str' => (string) $gid,
5347 'user' => $user_info
5350 return api_format_data("lists", $type, ['lists' => $list]);
5353 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5356 * Add a new group to the database.
5358 * @param string $name Group name
5359 * @param int $uid User ID
5360 * @param array $users List of users to add to the group
5364 function group_create($name, $uid, $users = [])
5366 // error if no name specified
5368 throw new BadRequestException('group name not specified');
5371 // get data of the specified group name
5373 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5377 // error message if specified group name already exists
5378 if (DBM::is_result($rname)) {
5379 throw new BadRequestException('group name already exists');
5382 // check if specified group name is a deleted group
5384 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5388 // error message if specified group name already exists
5389 if (DBM::is_result($rname)) {
5390 $reactivate_group = true;
5394 $ret = Group::create($uid, $name);
5396 $gid = Group::getIdByName($uid, $name);
5398 throw new BadRequestException('other API error');
5402 $erroraddinguser = false;
5404 foreach ($users as $user) {
5405 $cid = $user['cid'];
5406 // check if user really exists as contact
5408 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5412 if (count($contact)) {
5413 Group::addMember($gid, $cid);
5415 $erroraddinguser = true;
5416 $errorusers[] = $cid;
5420 // return success message incl. missing users in array
5421 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5423 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5427 * Create the specified group with the posted array of contacts.
5429 * @param string $type Return type (atom, rss, xml, json)
5431 * @return array|string
5433 function api_friendica_group_create($type)
5437 if (api_user() === false) {
5438 throw new ForbiddenException();
5442 $user_info = api_get_user($a);
5443 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5444 $uid = $user_info['uid'];
5445 $json = json_decode($_POST['json'], true);
5446 $users = $json['user'];
5448 $success = group_create($name, $uid, $users);
5450 return api_format_data("group_create", $type, ['result' => $success]);
5452 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5455 * Create a new group.
5457 * @param string $type Return type (atom, rss, xml, json)
5459 * @return array|string
5460 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5462 function api_lists_create($type)
5466 if (api_user() === false) {
5467 throw new ForbiddenException();
5471 $user_info = api_get_user($a);
5472 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5473 $uid = $user_info['uid'];
5475 $success = group_create($name, $uid);
5476 if ($success['success']) {
5478 'name' => $success['name'],
5479 'id' => intval($success['gid']),
5480 'id_str' => (string) $success['gid'],
5481 'user' => $user_info
5484 return api_format_data("lists", $type, ['lists'=>$grp]);
5487 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5490 * Update the specified group with the posted array of contacts.
5492 * @param string $type Return type (atom, rss, xml, json)
5494 * @return array|string
5496 function api_friendica_group_update($type)
5500 if (api_user() === false) {
5501 throw new ForbiddenException();
5505 $user_info = api_get_user($a);
5506 $uid = $user_info['uid'];
5507 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5508 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5509 $json = json_decode($_POST['json'], true);
5510 $users = $json['user'];
5512 // error if no name specified
5514 throw new BadRequestException('group name not specified');
5517 // error if no gid specified
5519 throw new BadRequestException('gid not specified');
5523 $members = Contact::getByGroupId($gid);
5524 foreach ($members as $member) {
5525 $cid = $member['id'];
5526 foreach ($users as $user) {
5527 $found = ($user['cid'] == $cid ? true : false);
5529 if (!isset($found) || !$found) {
5530 Group::removeMemberByName($uid, $name, $cid);
5535 $erroraddinguser = false;
5537 foreach ($users as $user) {
5538 $cid = $user['cid'];
5539 // check if user really exists as contact
5541 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5546 if (count($contact)) {
5547 Group::addMember($gid, $cid);
5549 $erroraddinguser = true;
5550 $errorusers[] = $cid;
5554 // return success message incl. missing users in array
5555 $status = ($erroraddinguser ? "missing user" : "ok");
5556 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5557 return api_format_data("group_update", $type, ['result' => $success]);
5560 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5563 * Update information about a group.
5565 * @param string $type Return type (atom, rss, xml, json)
5567 * @return array|string
5568 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5570 function api_lists_update($type)
5574 if (api_user() === false) {
5575 throw new ForbiddenException();
5579 $user_info = api_get_user($a);
5580 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5581 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5582 $uid = $user_info['uid'];
5584 // error if no gid specified
5586 throw new BadRequestException('gid not specified');
5589 // get data of the specified group id
5590 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5591 // error message if specified gid is not in database
5593 throw new BadRequestException('gid not available');
5596 if (Group::update($gid, $name)) {
5599 'id' => intval($gid),
5600 'id_str' => (string) $gid,
5601 'user' => $user_info
5604 return api_format_data("lists", $type, ['lists' => $list]);
5608 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5612 * @param string $type Return type (atom, rss, xml, json)
5614 * @return array|string
5616 function api_friendica_activity($type)
5620 if (api_user() === false) {
5621 throw new ForbiddenException();
5623 $verb = strtolower($a->argv[3]);
5624 $verb = preg_replace("|\..*$|", "", $verb);
5626 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5628 $res = Item::performLike($id, $verb);
5631 if ($type == "xml") {
5636 return api_format_data('ok', $type, ['ok' => $ok]);
5638 throw new BadRequestException('Error adding activity');
5642 /// @TODO move to top of file or somewhere better
5643 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5644 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5645 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5646 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5647 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5648 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5649 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5650 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5651 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5652 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5655 * @brief Returns notifications
5657 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5658 * @return string|array
5660 function api_friendica_notification($type)
5664 if (api_user() === false) {
5665 throw new ForbiddenException();
5668 throw new BadRequestException("Invalid argument count");
5670 $nm = new NotificationsManager();
5672 $notes = $nm->getAll([], "+seen -date", 50);
5674 if ($type == "xml") {
5676 foreach ($notes as $note) {
5677 $xmlnotes[] = ["@attributes" => $note];
5683 return api_format_data("notes", $type, ['note' => $notes]);
5687 * POST request with 'id' param as notification id
5689 * @brief Set notification as seen and returns associated item (if possible)
5691 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5692 * @return string|array
5694 function api_friendica_notification_seen($type)
5697 $user_info = api_get_user($a);
5699 if (api_user() === false || $user_info === false) {
5700 throw new ForbiddenException();
5703 throw new BadRequestException("Invalid argument count");
5706 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5708 $nm = new NotificationsManager();
5709 $note = $nm->getByID($id);
5710 if (is_null($note)) {
5711 throw new BadRequestException("Invalid argument");
5714 $nm->setSeen($note);
5715 if ($note['otype']=='item') {
5716 // would be really better with an ItemsManager and $im->getByID() :-P
5717 $item = Item::selectFirst(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5718 if (DBM::is_result($$item)) {
5719 // we found the item, return it to the user
5720 $ret = api_format_items([$item], $user_info, false, $type);
5721 $data = ['status' => $ret];
5722 return api_format_data("status", $type, $data);
5724 // the item can't be found, but we set the note as seen, so we count this as a success
5726 return api_format_data('result', $type, ['result' => "success"]);
5729 /// @TODO move to top of file or somewhere better
5730 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5731 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5734 * @brief update a direct_message to seen state
5736 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5737 * @return string|array (success result=ok, error result=error with error message)
5739 function api_friendica_direct_messages_setseen($type)
5742 if (api_user() === false) {
5743 throw new ForbiddenException();
5747 $user_info = api_get_user($a);
5748 $uid = $user_info['uid'];
5749 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5751 // return error if id is zero
5753 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5754 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5757 // error message if specified id is not in database
5758 if (!dba::exists('mail', ['id' => $id, 'uid' => $uid])) {
5759 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5760 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5763 // update seen indicator
5764 $result = dba::update('mail', ['seen' => true], ['id' => $id]);
5768 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5769 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5771 $answer = ['result' => 'error', 'message' => 'unknown error'];
5772 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5776 /// @TODO move to top of file or somewhere better
5777 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5780 * @brief search for direct_messages containing a searchstring through api
5782 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5783 * @param string $box
5784 * @return string|array (success: success=true if found and search_result contains found messages,
5785 * success=false if nothing was found, search_result='nothing found',
5786 * error: result=error with error message)
5788 function api_friendica_direct_messages_search($type, $box = "")
5792 if (api_user() === false) {
5793 throw new ForbiddenException();
5797 $user_info = api_get_user($a);
5798 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5799 $uid = $user_info['uid'];
5801 // error if no searchstring specified
5802 if ($searchstring == "") {
5803 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5804 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5807 // get data for the specified searchstring
5809 "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",
5811 dbesc('%'.$searchstring.'%')
5814 $profile_url = $user_info["url"];
5816 // message if nothing was found
5817 if (!DBM::is_result($r)) {
5818 $success = ['success' => false, 'search_results' => 'problem with query'];
5819 } elseif (count($r) == 0) {
5820 $success = ['success' => false, 'search_results' => 'nothing found'];
5823 foreach ($r as $item) {
5824 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5825 $recipient = $user_info;
5826 $sender = api_get_user($a, normalise_link($item['contact-url']));
5827 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5828 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5829 $sender = $user_info;
5832 if (isset($recipient) && isset($sender)) {
5833 $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'
5849 * @return string|array
5851 function api_friendica_profile_show($type)
5855 if (api_user() === false) {
5856 throw new ForbiddenException();
5860 $profile_id = (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 ($profile_id != 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
5887 foreach ($r as $rr) {
5888 $profile = api_format_items_profiles($rr);
5890 // select all users from contact table, loop and prepare standard return for user data
5893 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5895 intval($rr['profile_id'])
5898 foreach ($nurls as $nurl) {
5899 $user = api_get_user($a, $nurl['nurl']);
5900 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5902 $profile['users'] = $users;
5904 // add prepared profile data to array for final return
5905 if ($type == "xml") {
5906 $profiles[$k++ . ":profile"] = $profile;
5908 $profiles[] = $profile;
5912 // return settings, authenticated user and profiles data
5913 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5915 $result = ['multi_profiles' => $multi_profiles ? true : false,
5916 'global_dir' => $directory,
5917 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5918 'profiles' => $profiles];
5919 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5921 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5924 * Returns a list of saved searches.
5926 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5928 * @param string $type Return format: json or xml
5930 * @return string|array
5932 function api_saved_searches_list($type)
5934 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5937 while ($term = $terms->fetch()) {
5939 'created_at' => api_date(time()),
5940 'id' => intval($term['id']),
5941 'id_str' => $term['id'],
5942 'name' => $term['term'],
5944 'query' => $term['term']
5950 return api_format_data("terms", $type, ['terms' => $result]);
5953 /// @TODO move to top of file or somewhere better
5954 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5957 @TODO Maybe open to implement?
5959 [pagename] => api/1.1/statuses/lookup.json
5960 [id] => 605138389168451584
5961 [include_cards] => true
5962 [cards_platform] => Android-12
5963 [include_entities] => true
5964 [include_my_retweet] => 1
5966 [include_reply_count] => true
5967 [include_descendent_reply_count] => true
5971 Not implemented by now:
5972 statuses/retweets_of_me
5977 account/update_location
5978 account/update_profile_background_image
5981 friendica/profile/update
5982 friendica/profile/create
5983 friendica/profile/delete
5985 Not implemented in status.net:
5986 statuses/retweeted_to_me
5987 statuses/retweeted_by_me
5988 direct_messages/destroy
5990 account/update_delivery_device
5991 notifications/follow